Terminal to achieve large file upload has been a relatively difficult technology, which involves the backend and front-end interaction, stability and flow size, and the principle of implementation of everyone has their own ideas, back-end mainstream use of more than HTTP to achieve, because most of the implementation of the breakpoint download. But stability can not be guaranteed, once disconnected, can not be continued transmission. So we have to adopt another popular approach, TCP upload large files.
On the Internet to find some information, most are breakpoints to download, and then is a separate C # side of the upload received, or HTTP, or only the Android side, because the task is tight so the preferred solution before the first is to achieve the HTTP file upload, the terminal using the Post method, the file directly to the back end, The back end is obtained through file.
Android side:
Requestparams params = new Requestparams ();
File File = GetTempFile ()//Get local file
try {
params.put ("file", file);
} catch (FileNotFoundException E1) {
e1.printstacktrace ();
}
Asynchttputil.post (URL + "/upload", params, new Jsonhttpresponsehandler () {
...)
Back end:
var file = request.files["file"];
File. SaveAs (Upfilename);
There are other better ways to do this, and you can Liu in and out of the file file format. In the good case of the network, but the network almost often uploaded half off the line or a number of client uploads are not connected to the situation, for large files extremely unstable, so hurriedly develop TCP protocol file breakpoint upload.
Also has the netizen to realize the HTTP breakpoint upload, since the big file is not good, that will divide the file into the small file to upload, the pure net Main method:
Upload:
bool result = true;
Long cruuent = 0;
FileStream fstream = new FileStream (FileName, FileMode.Open, FileAccess.Read);
BinaryReader breader = new BinaryReader (fstream);
Analog breakpoint upload, first upload only 100 bytes long length = 100;
FileName = filename.substring (Filename.lastindexof (' \ = ') + 1);
#region start uploading file try {byte[] data; #region split file upload for (; cruuent <= length; cruuent = cruuent + byteCount) {if (cruuent + byteCount > Len
GTH) {data = new Byte[convert.toint64 ((length-cruuent))];
Breader.read (data, 0, Convert.ToInt32 (length-cruuent));
else {data = new Byte[bytecount];
Breader.read (data, 0, ByteCount);
try {Hashtable parms = new Hashtable (); Parms.
ADD ("filename", filename); Parms. ADD ("NPOs", cruuent.
ToString ());
byte[] Byremoteinfo = postdata (Serverpath + "uploadserver.aspx", data, parms); catch (Exception ex) {msg = Ex.
ToString ();
result = false;
Break ' #endregion} ' catch (Exception ex) {msg = ex.
ToString ();
result = false;
finally {breader.close ();
Fstream.close (); } GC.
Collect ();
The
First splits the file into small streams, npos the location of the breakpoint, the size that has been uploaded, and then loops over all the packages.
Background receive:
///<summary>///save file (get file name from URL parameter, current pointer, save file stream to current pointer)///if this is the first upload, the current pointer is 0, and generation
Code execution is the same as the continuation, except that the pointer is not offset///</summary> public void Saveuploadfile () {string filename = request.params["filename"];
Long NPOs = Convert.toint64 (request.params["NPOs"]);
int uploadlength = Convert.ToInt32 (Request.InputStream.Length);
String path = Server.MapPath ("/uploadserver");
filename = path + "//upload//" + filename;
FileStream fstream = new FileStream (FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
Offset pointer Fstream.seek (NPOs, Seekorigin.begin);
Gets the file stream from the client's request BinaryReader Breader = new BinaryReader (request.inputstream);
try {byte[] data = new Byte[uploadlength];
Breader.read (data, 0, uploadlength);
Fstream.write (data, 0, uploadlength);
Catch {//todo add exception handling} finally {//release stream Fstream.close ();
Breader.close (); }
}
Emphasis in Fstream.seek (NPOs, Seekorigin.begin); Receive the save from the breakpoint location.
Interested can be achieved by themselves.
Now mainly talk about client TCP upload, background TCP reception, the main idea for: The Android side read the file name, file size upload to the server (filename must be globally unique), the server will be based on the file name query whether uploaded, if uploaded, Transfer the file size that is the breakpoint location to the terminal, the terminal to save the location of the breakpoint, and then read the file from the breakpoint location intermittent upload, until all completed. If it's not uploaded, the server creates a cache file sink.
Look at the code android:
String head = "length=" + uploadfile.length () + "; filename=" + filename socket socket = new Socket ("192.168.0.123", 708
0);
OutputStream OutStream = Socket.getoutputstream (); Outstream.write (Head.getbytes ()),//send Pushbackinputstream instream = new Pushbackinputstream (Socket.getinputstream (
));
String response = Streamtool.readline (instream);//Read string[] items = Response.split (";"); Final string position = Items[0].substring (items[0].indexof ("=") + 1);/Breakpoint Position final String serviceurl = Items[1].subs
Tring (items[1].indexof ("=") + 1);//Save to Server path Randomaccessfile Fileoutstream = new Randomaccessfile (UploadFile, "R");
Fileoutstream.seek (integer.valueof (position))//Read file from breakpoint location byte[] buffer = new byte[1024];
int len =-1; int length = integer.valueof (position),//already uploaded size, used to display while (len = fileoutstream.read (buffer))!=-1) {O
Utstream.write (buffer, 0, Len);
length = = Len;
msg = new Message (); Msg.getdata (). Putint ("size", length);
Update the Upload Progress Handler.sendmessage (msg); if (length = = Uploadfile.length ()) {//if equal, the upload succeeds} fileoutstream.close (); Outstream.close (); Instream.close ();
Socket.close ();
Back-end Processing:
private static TcpListener listener;//server Monitor
ipaddress iphost = Ipaddress.any;
Listener = new TcpListener (iphost, 7080);
Listener. Start ()//Open listening
Socket remotesocketclient = listener. AcceptSocket ();
device = new device (remotesocketclient);
Open a thread to handle
Threaddev = new Thread (new ThreadStart (device). Scan));
Device.curentthread = Threaddev;
Threaddev. IsBackground = true;
Threaddev. Start ();
Scan Processing Method:
string[] items = Strgetcontent.split (';');
String filelength = Items[0]. Substring (Items[0]. IndexOf ("=") + 1);
string filename = items[1]. Substring (Items[1]. IndexOf ("=") + 1);
File save full path
FilePath = Path.Combine (directorypath, filename);
Breakpoint position
Long position = 0;
if (file.exists (FilePath))
{
using (FileStream reader = new FileStream (FilePath, FileMode.Open, FileAccess.Read, Fileshare.none))
{
position = reader. Length;
}
}
Return message
response = "position=" + position + "; serviceurl=" + Dirpath + "/" + filename);
After the server receives the client's request information, it returns the response information to the client:;p osition=0
//serviceurl The location of the file saved by the waiter/playfiles/video/2016/07/04/1141142221.mp4
buffersend = Encoding.UTF8.GetBytes (response);
Remotesocketclient.send (Buffersend);
And then process the continuation content:
Get file content
byte[] buffer = new Byte[buffersize];
int received = 0;
Long receive, length = long. Parse (filelength);
FileInfo file = new FileInfo (filePath);
using (FileStream writer = file. Open (file. Exists? FileMode.Append:FileMode.CreateNew, FileAccess.Write, Fileshare.none))
{
receive = writer. Length;
while (receive < length)
{
if (Received = remotesocketclient.receive (buffer) = = 0)
{
Program.messageadd ("IP" + remoteSocketClient.RemoteEndPoint.ToString () + "" Receive pause!) ");
break;
Writer. Write (buffer, 0, received);
Writer. Flush ();
Receive + = (long) received;
}
}
if (receive = = length)
{
program.messageadd ("IP" + remoteSocketClient.RemoteEndPoint.ToString () + "receive" + FileName + "Complete!" ");
}
The main principle is to upload and receive from the breakpoint position.
Here just talk about the most important code features, there are many details to deal with, such as the terminal to show progress, so also to save the progress, the back-end files will be misplaced, there are multiple file upload will not be messy, multiple client upload is to create a new thread or a wire pool to deal with and so
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.