Getting started with Android: File Upload

Source: Internet
Author: User

File Upload is divided into two parts:

(1) server: Use fileupload + common. Io to upload files;

(2) client: the HTTP Request Header for simulating File Upload;



I. server code

Fileservlet. Java

Package Org. xiazdong. servlet; import Java. io. file; import Java. io. ioexception; import Java. util. list; import javax. servlet. servletexception; import javax. servlet. annotation. webservlet; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import Org. apache. commons. fileupload. fileitem; import Org. apache. commons. fileupload. disk. diskf Ileitemfactory; import Org. apache. commons. fileupload. servlet. servletfileupload; @ webservlet ("/fileservlet") public class fileservlet extends httpservlet {protected void doget (httpservletrequest request, response) throws handle, ioexception {} protected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {diskfileitemf Actory factory = new diskfileitemfactory (); servletfileupload upload = new servletfileupload (factory); upload. setfilesizemax (1024*1024); // set the maximum size of the uploaded file. Try {list <fileitem> items = upload. parserequest (request); // get all the data in the form for (fileitem item: Items) {If (! Item. isformfield () {// If the uploaded file is string name = "d :\\" + item. getname (). substring (item. getname (). lastindexof ('\') + 1); string filename = Name; system. out. println (filename); file F = new file (filename); // save it to disk D. write (f); system. out. println ("uploaded successfully") ;}} catch (exception e) {e. printstacktrace ();}}}

Browser code:

<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> 

2. Client preparation and core code

1. Preparations


Because the client needs to simulate an HTTP request, we can first look at the HTTP request for file upload:

Post/Server/fileservlet HTTP/1.1
Accept :*/*
Referer: http: // localhost: 8080/Server/2.html
Accept-language: ZH-CN
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; wow64; Trident/4.0; slcc2 ;. net CLR 2.0.50727 ;. net CLR 3.5.30729 ;. net CLR 3.0.30729; Media Center PC 6.0 ;. net4.0e ;. net4.0c; infopath.3)
Content-Type: multipart/form-data; boundary = --------------------------- 7dc372520758 // The separator is used to separate multiple files and parameters.
Accept-encoding: gzip, deflate
HOST: localhost: 8080
Content-Length: 14610
Connection: keep-alive
Cache-control: No-Cache

----------------------------- 7dc372520758
Content-Disposition: Form-data; name = "FILENAME"; filename = "D: \ lv6.gif"
Content-Type: image/GIF
File Content
----------------------------- 7dc372520758 -- // Add two more values at the end --

From this we can see that this HTTP request is difficult to simulate. Here we encapsulate a helper class, which is implemented by Teacher Li fuming. We can use it directly:

Httprequestutil. uploadfile (string path, Map <string, string> Params, formfile file)

Path: URL

Params: Common Parameters

File: File

Httprequestutil. uploadfiles (string path, Map <string, string> Params, formfile [] files)

Path: URL

Params: Common Parameters

Files: multiple files


Formfile. Java

Package COM. xiazdong. netword. HTTP. util; import Java. io. file; import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. inputstream;/*** Upload File */public class formfile {/* Upload File data */private byte [] data; private inputstream instream; private file; /* file name */private string filname;/* request parameter name */private string parametername;/* content type */private string contenttype = "application/octet- Stream "; /*** this function is used to transmit the control parameter name * @ Param filname * @ Param data * @ Param parametername HTML of a small file * @ Param contenttype */Public formfile (string filname, byte [] data, string parametername, string contenttype) {This. data = data; this. filname = filname; this. parametername = parametername; If (contenttype! = NULL) This. contenttype = contenttype;}/*** this function is used to transmit large files * @ Param filname * @ Param file * @ Param parametername * @ Param contenttype */Public formfile (string filname, file file, string parametername, string contenttype) {This. filname = filname; this. parametername = parametername; this. file = file; try {This. instream = new fileinputstream (File);} catch (filenotfoundexception e) {e. printstacktrace ();} If (C Ontenttype! = NULL) This. contenttype = contenttype;} public file GetFile () {return file;} public inputstream getinstream () {return instream;} public byte [] getdata () {return data ;} public String getfilname () {return filname;} public void setfilname (string filname) {This. filname = filname;} Public String getparametername () {return parametername;} public void setparametername (string parametername) {This. parametername = parametername;} Public String getcontenttype () {return contenttype;} public void setcontenttype (string contenttype) {This. contenttype = contenttype ;}}


Httprequestutil. Java

Package COM. xiazdong. netword. HTTP. util; import Java. io. bufferedreader; import Java. io. bytearrayoutputstream; import Java. io. inputstream; import Java. io. inputstreamreader; import Java. io. outputstream; import java.net. httpurlconnection; import java.net. inetaddress; import java.net. socket; import java.net. URL; import java.net. urlconnection; import java.net. urlencoder; import Java. util. hashmap; import Java. util. map; Import Java. util. map. entry; import Java. util. set;/** this class is used to send HTTP requests. **/public class httprequestutil {/*** submits data directly to the server through the HTTP protocol. The following form submission function is implemented: * <form method = post action = "http: // 192.168.0.200: 8080/ssi/fileload/test. do "enctype =" multipart/form-Data "> <input type =" text "name =" name "> <input type =" text "name =" ID "> <Input type = "file" name = "imagefile"/> <input type = "file" name = "Zip"/> </form> * @ Param path PATH (Note: Avoid using a path test like localhost or 127.0.0.1 because it will point to the phone simulator and you can use a path test like http://www.itcast.cn or http: // 192.168.1.10: 8080) * @ Param Params the request parameter key is the parameter name, and the value is the parameter value * @ Param File Upload File */public static Boolean uploadfiles (string path, Map <string, string> Params, formfile [] files) throws exception {final string boundary = "--------------------------- 7da1_7580612"; // data separation line final string endline = "--" + boundary + "-- \ r \ N "; // data end sign int filedatalength = 0; If (files! = NULL & files. length! = 0) {for (formfile uploadfile: Files) {// obtain the total length of the file type data stringbuilder fileexplain = new stringbuilder (); fileexplain. append ("--"); fileexplain. append (Boundary); fileexplain. append ("\ r \ n"); fileexplain. append ("content-Disposition: Form-data; name = \" "+ uploadfile. getparametername () + "\"; filename = \ "" + uploadfile. getfilname () + "\" \ r \ n "); fileexplain. append ("Content-Type:" + uploadfile. getcontenttype () + "\ r \ N \ r \ n "); fileexplain. append (" \ r \ n "); filedatalength + = fileexplain. Length (); If (uploadfile. getinstream ()! = NULL) {filedatalength + = uploadfile. getFile (). length ();} else {filedatalength + = uploadfile. getdata (). length ;}} stringbuilder textentity = new stringbuilder (); If (Params! = NULL &&! Params. isempty () {for (map. entry <string, string> entry: Params. entryset () {// construct the object data textentity of the text type parameter. append ("--"); textentity. append (Boundary); textentity. append ("\ r \ n"); textentity. append ("content-Disposition: Form-data; name = \" "+ entry. getkey () + "\" \ r \ n "); textentity. append (entry. getvalue (); textentity. append ("\ r \ n") ;}// calculates the total length of the object data transmitted to the server. Int datalength = textentity. tostring (). getbyte S (). Length + filedatalength + endline. getbytes (). length; Url url = new URL (PATH); int Port = URL. getport () =-1? 80: URL. getport (); Socket socket = new socket (inetaddress. getbyname (URL. gethost (), Port); outputstream outstream = socket. getoutputstream (); // The string requestmethod = "Post" + URL sent in the HTTP request header is completed below. getpath () + "HTTP/1.1 \ r \ n"; outstream. write (requestmethod. getbytes (); string accept = "accept: image/GIF, image/JPEG, image/pjpeg, image/pjpeg, application/X-Shockwave-flash, application/XAML + XML, applica Tion/vnd. MS-xpsdocument, application/X-MS-xbap, application/X-MS-application, application/vnd. MS-Excel, application/vnd. MS-PowerPoint, application/MSWord, */* \ r \ n "; outstream. write (accept. getbytes (); string Language = "Accept-language: ZH-CN \ r \ n"; outstream. write (language. getbytes (); string contenttype = "Content-Type: multipart/form-data; boundary =" + boundary + "\ r \ n"; outstream. write (contenttyp E. getbytes (); string contentlength = "Content-Length:" + datalength + "\ r \ n"; outstream. write (contentlength. getbytes (); string alive = "connection: keep-alive \ r \ n"; outstream. write (alive. getbytes (); string host = "Host:" + URL. gethost () + ":" + port + "\ r \ n"; outstream. write (host. getbytes (); // After writing the HTTP Request Header, write another carriage return outstream Based on the HTTP protocol. write ("\ r \ n ". getbytes (); // send object data of all text types out of outstream. write (texten Tity. tostring (). getbytes (); // send object data of all file types if (files! = NULL & files. length! = 0) {for (formfile uploadfile: Files) {stringbuilder fileentity = new stringbuilder (); fileentity. append ("--"); fileentity. append (Boundary); fileentity. append ("\ r \ n"); fileentity. append ("content-Disposition: Form-data; name = \" "+ uploadfile. getparametername () + "\"; filename = \ "" + uploadfile. getfilname () + "\" \ r \ n "); fileentity. append ("Content-Type:" + uploadfile. getcontenttype () + "\ r \ n"); outstream. W Rite (fileentity. tostring (). getbytes (); If (uploadfile. getinstream ()! = NULL) {byte [] buffer = new byte [1024]; int Len = 0; while (LEN = uploadfile. getinstream (). read (buffer, 0, 1024 ))! =-1) {outstream. write (buffer, 0, Len);} uploadfile. getinstream (). close ();} else {outstream. write (uploadfile. getdata (), 0, uploadfile. getdata (). length);} outstream. write ("\ r \ n ". getbytes () ;}}// the end mark of the sent data, indicating that the data has ended outstream. write (endline. getbytes (); bufferedreader reader = new bufferedreader (New inputstreamreader (socket. getinputstream (); If (reader. readline (). indexof ("200") =-1) {// read the number returned by the Web Server Judge whether the request code is 200. If it is not 200, return false if the request fails;} outstream. flush (); outstream. close (); reader. close (); socket. close (); Return true;}/*** submit data to the server * @ Param path upload path (Note: Do not test using a path like localhost or 127.0.0.1, because it will point to the phone simulator, you can test using a path like http://www.itcast.cn or http: // 192.168.1.10: 8080) * @ Param Params request parameter key for Parameter Name, value is the parameter value * @ Param file */public static Boolean uploadfile (string path, Map <string, string> Params, Formfile file) throws exception {return uploadfiles (path, Params, new formfile [] {file });} /*** convert the input stream into a byte array * @ Param instream * @ return * @ throws exception */public static byte [] read2byte (inputstream instream) throws exception {bytearrayoutputstream outsteam = new bytearrayoutputstream (); byte [] buffer = new byte [1024]; int Len = 0; while (LEN = instream. read (buffer ))! =-1) {outsteam. write (buffer, 0, Len);} outsteam. close (); instream. close (); Return outsteam. tobytearray ();}/*** convert the input stream into a string * @ Param instream * @ return * @ throws exception */public static string read2string (inputstream instream) throws exception {bytearrayoutputstream outsteam = new bytearrayoutputstream (); byte [] buffer = new byte [1024]; int Len = 0; while (LEN = instream. read (buffer ))! =-1) {outsteam. write (buffer, 0, Len);} outsteam. close (); instream. close (); return new string (outsteam. tobytearray (), "UTF-8 ");}}


2. Core code


Formfile = new formfile (file. getname (), file, "document", "text/plain"); // "document" indicates the control name, and "text/plain" indicates the mimetypeboolean issuccess = httprequestutil of the file. uploadfile ("http: // 192.168.0.103: 8080/Server/fileservlet", null, formfile );

Iii. client code





Androidmanifest. xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><uses-permission android:name="android.permission.INTERNET"/>



Mainactivity. Java

Package Org. xiazdong. network. fileupload; import Java. io. file; import android. app. activity; import android. OS. bundle; import android. OS. environment; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. toast; import COM. xiazdong. netword. HTTP. util. formfile; import COM. xiazdong. netword. HTTP. util. httprequestutil; public class mainactivity extends activity {private edittext filename; private button; private onclicklistener listener = new onclicklistener () {@ overridepublic void onclick (view v) {string fname = filename. gettext (). tostring (); If (environment. getexternalstoragestate (). equals (environment. media_mounted) | environment. getexternalstoragestate (). equals (environment. media_mounted_read_only) {file = new file (environment. getexternalstoragedirectory (), fname); // obtain the sdcard file if (file. exists () {formfile = new formfile (file. getname (), file, "document", "text/plain"); try {Boolean issuccess = httprequestutil. uploadfile ("http: // 192.168.0.103: 8080/Server/fileservlet", null, formfile); If (issuccess) {toast. maketext (mainactivity. this, "the file is uploaded successfully", toast. length_short ). show ();} else {toast. maketext (mainactivity. this, "File Upload Failed", toast. length_short ). show () ;}} catch (exception e) {e. printstacktrace () ;}} else {toast. maketext (mainactivity. this, "file does not exist", toast. length_short ). show () ;}} else {toast. maketext (mainactivity. this, "sdcard does not exist", toast. length_short ). show () ;}};@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); filename = (edittext) This. findviewbyid (R. id. filename); button = (button) This. findviewbyid (R. id. button); button. setonclicklistener (listener );}}



Related Article

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.