Android uploads files to server and displays progress bar _android

Source: Internet
Author: User

Recently in doing upload file services, a simple look at the online tutorials. Share the code with practice.

Because most of the internet does not have the service-side code, this can not ah, no service-side how to debug it.

Ok, first go to the code.

Android upload is relatively simple, the main use of the HttpURLConnection class, and then add a progress bar component.

Private ProgressBar Mpgbar; 
  Class Uploadtask extends asynctask<object,integer,void>{private dataoutputstream outputstream = null; 
  Private String FileName; 
  Private String URI; 
  Private String mlineend = "\ r \ n"; 
  Private String Mtwohyphens = "--"; 
  Private String boundary = "* * *"; 
  File UploadFile; Long mttotalsize; 
   Get size of file, bytes public uploadtask (String filename,string uri) {this.filename = FileName; 
   This.uri = URI; 
    uploadfile= new File (FileName); 
  Mttotalsize = Uploadfile.length (); /** * Start uploading file * @param objects * @return/@Override protected Void doinbackground (Object ... 
   objects) {Long length = 0; 
   int Mbytesread, mbytesavailable, mbuffersize; 
   byte[] buffer; int MaxBufferSize = 256 * 1024;//256KB try{fileinputstream fileinputstream = new FileInputStream (New File (fil 
 
    ename)); 
 
    URL url = new URL (URI); HttpURLConnection con = (httpurlconnection) URL.OPenconnection (); 
 
    If necessary, you can set cookies//Conn.setrequestproperty ("Cookie", "jsessionid=" +cookie); Set size of every block for post Con.setchunkedstreamingmode (256 * 1024);//256KB/Allow Inputs & O 
    Utputs Con.setdoinput (TRUE); 
    Con.setdooutput (TRUE); 
 
    Con.setusecaches (FALSE); 
    Enable Post Method Con.setrequestmethod ("post"); 
    Con.setrequestproperty ("Connection", "keep-alive"); 
    Con.setrequestproperty ("Charset", "UTF-8"); 
 
    Con.setrequestproperty ("Content-type", "multipart/form-data;boundary=" + boundary); 
    OutputStream = new DataOutputStream (Con.getoutputstream ()); 
    Outputstream.writebytes (mtwohyphens + boundary + mlineend); Outputstream.writebytes ("Content-disposition:form-data; Name=\ "File\"; 
    Filename=\ "" + fileName + "\" "+ mlineend); 
    Outputstream.writebytes ("Content-type:application/octet-stream \ r \ n"); 
 
    Outputstream.writebytes (Mlineend); Mbytesavailable = FileiNputstream.available (); 
    Mbuffersize = Math.min (mbytesavailable, MaxBufferSize); 
 
    Buffer = new Byte[mbuffersize]; 
 
    Read File Mbytesread = fileinputstream.read (buffer, 0, mbuffersize); 
     while (Mbytesread > 0) {outputstream.write (buffer, 0, mbuffersize); 
 
     length + = Mbuffersize; 
 
     Publishprogress ((int) ((length *)/mttotalsize)); 
 
     mbytesavailable = Fileinputstream.available (); 
 
     Mbuffersize = Math.min (mbytesavailable, MaxBufferSize); 
    Mbytesread = fileinputstream.read (buffer, 0, mbuffersize); 
    } outputstream.writebytes (Mlineend); 
    Outputstream.writebytes (mtwohyphens + boundary + mtwohyphens + mlineend); 
 
    Publishprogress (100); 
    Responses from the "server" (Code and message) int serverresponsecode = Con.getresponsecode (); 
    String serverresponsemessage = Con.getresponsemessage (); 
    Fileinputstream.close (); 
    Outputstream.flush (); 
 
   Outputstream.close (); catch (ExCeption ex) {ex.printstacktrace (); 
   LOG.V (TAG, "uploaderror"); 
  return null; 
  } @Override protected void Onprogressupdate (Integer ... progress) {mpgbar.setprogress (progress[0]); 

 } 
 }

The main process is to inherit asynctask, and then use HttpURLConnection to upload files. The code is relatively simple, it will not be explained.
One of the things to note is the need to

Copy Code code as follows:
Outputstream.writebytes ("Content-disposition:form-data; Name=\ "File\"; Filename=\ "" + fileName + "\" "+ mlineend);

Set name to the parameter name of the Web request, because my service side is setting the file as a filename, so I can fill in files directly. So we can make corresponding changes according to the actual situation.

Then on the server side code, the server mainly uses the Status 2 framework for the request. Then we need to encapsulate it.

Upload file Collection 
 private list<file> file; 
 Upload file name Collection 
 private list<string> filefilename; 
 Upload file content type collection 
 private list<string> filecontenttype; 
 
 Public list<file> GetFile () {return 
  File; 
 } 
 
 public void Setfile (list<file> file) { 
  this.file = file; 
 } 
 
 Public list<string> Getfilefilename () {return 
  filefilename; 
 } 
 
 public void Setfilefilename (list<string> filefilename) { 
  this.filefilename = filefilename; 
 } 
 
 Public list<string> Getfilecontenttype () {return 
  filecontenttype; 
 } 
 
 public void Setfilecontenttype (list<string> filecontenttype) { 
  this.filecontenttype = Filecontenttype; 
 } 

A multiple file Upload method is used to define the list collection.
Then process the file upload action, because it is the test method. This is defined as testupload.

Public String Testupload () throws exception{ 
  System.out.println ("Success"); 
  UploadFile (0); 
  return SUCCESS; 
 } 

Here is not much to complete the action, now need to start to write the method of uploading uploadfile (int index), because the definition file for multiple files upload, and we upload only upload a file, so here the parameter is 0

/** * Upload function * @param i * @return * @throws FileNotFoundException * @throws IOException */Private String uploadfile (int i) throws FileNotFoundException, IOException {try {inputst 
 
   Ream in = new FileInputStream (File.get (i)); 
    
   String dir = servletactioncontext.getrequest (). Getrealpath (Uploaddir); 
 
   String dir = "d://uploaddata/"; 
 
   File UploadFile = new file (Dir,stringutils.getuuid () +getfile (This.getfilefilename (). get (i))); 
 
   OutputStream out = new FileOutputStream (uploadfile); 
 
   byte[] buffer = new byte[1024 * 1024]; 
   int length; 
   while (length = in.read (buffer) > 0) {out.write (buffer, 0, length); 
   } in.close (); 
   Out.close (); 
  Then the calculation return Uploadfile.getabsolutepath (); 
  catch (FileNotFoundException ex) {ex.printstacktrace (); 
  catch (IOException ex) {ex.printstacktrace (); 
 return null; } 

The above method is to put the cached area of the file into the d://uploaddata/file, and then name in their own format, where I use the computer's UUID and file name to combine to ensure that I copied the file does not duplicate.
The true address of the file is returned after the final upload is successful.

OK, write to upload the file function is basically done. Finally, only the configuration action action is left.

OK, we open the Status.xml file for configuration

<!--system constants definition, define upload file character set encoding--> 
 <constant name= "struts.i18n.encoding" value= "Utf-8" ></constant> 
 <!--system constant definition, define upload file zero store path--> 
 <constant name= "Struts.multipart.saveDir" value= "C:\tmp\" ></ constant> 
 <constant name= "struts.multipart.maxSize" value= "10000000"/> 

This mainly defines the temporary storage location of the uploaded file, and then the size limit.
Everyone can be configured according to the actual situation.

Finally upload a picture of the effect.

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.