Android http File Upload-local + server one-stop Analysis

Source: Internet
Author: User
Tags http file upload sendfile

Android http File Upload-local + server one-stop Analysis

Local:

Let's take a look at the project structure.

MainActivity. java

Package com. huxq. uploadexample; import java. io. file; import android. annotation. suppressLint; import android. app. activity; import android. app. progressDialog; import android. OS. bundle; import android. OS. environment; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. view; import android. widget. toast; public class MainActivity extends Activity implements OnUploadLis Tener {// server path, replace with your own private String urlString = "http: // 192.168.1.2: 8080/UploadTest/Upload "; /*** Upload File Path */String filePath;/*** Upload File name */String fileName; ProgressDialog dialog;/*** when reading the file stream, the same progress is called back multiple times. With this flag, the ui is updated only when the progress is updated. */int oldProcess; @ SuppressLint ("HandlerLeak ") private Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {Log. I ("process", "process" + m Sg. arg1); dialog. setProgress (msg. arg1); // display dialogif (! Dialog. isShowing () {Log. I ("process", "show"); dialog. show ();} else {if (msg. arg1 = 100) {// prompts the user to upload the dialog. dismiss (); toast ("Upload complete! ") ;}};}; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initProgressDialog ();} public void upLoad (View v) {if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {// toast ("Upload"); String sdcardPath = Environment. getExternalStorageDirectory (). getAbsolutePath (); filePath = sdcardPath + "/K /"; File file = new File (filePath); // here I select the fifth File in the SORT K folder. You must upload the file based on your actual situation. Otherwise, an error will occur. FileName = file. list () [4]; filePath + = fileName; Log. I ("file. size "," size = "+ file. list (). length + "filePath" + filePath);} else {toast ("no memory card"); return;} new Thread () {public void run () {try {String response = HttpUtil. sendFile (urlString, filePath, fileName, MainActivity. this); Log. I ("response", "response" + response);} catch (Exception e) {e. printStackTrace ();}};}. start () ;}@ Overridepublic void onUpload (double process) {process = process * 100; int currentProcess = (int) process; dialog. setProgress (currentProcess); // avoid sending messages repeatedly. You can remove if to see what will happen if (currentProcess> oldProcess) {Message msg = handler. obtainMessage (); msg. arg1 = (int) process; handler. sendMessage (msg);} oldProcess = currentProcess;} public void initProgressDialog () {dialog = new ProgressDialog (this); dialog. setMax (100); dialog. setProgress (0); dialog. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); dialog. setCancelable (false); dialog. setCanceledOnTouchOutside (false); dialog. setTitle ("Uploading... ");} public void toast (String text) {Toast. makeText (getApplicationContext (), text, Toast. LENGTH_SHORT ). show ();}}
HttpUtil. java

Public static String sendFile (String urlPath, String filePath, String newName, OnUploadListener listener) throws Exception {String end = "\ r \ n"; String twoHyphens = "--"; string boundary = "*******"; URL url = new URL (urlPath); HttpURLConnection con = (HttpURLConnection) url. openConnection (); // set the parameter value of the setDoInput method to truecon for downloading. setDoInput (true); // set the parameter value of the setDoOutput method to truecon for upload. setDoOutput (true); // disable HttpURLCo Nnection uses cache con. setUseCaches (false); // the POST request must be capitalized con. setRequestMethod ("POST"); // set http request header information con. setRequestProperty ("Connection", "Keep-Alive"); con. setRequestProperty ("Charset", "UTF-8"); // when simulating a web page to upload a file to the server, each file must start with a separator, // The delimiter must be specified in the http request header. Boundary is any string, which is generally *** con. setRequestProperty ("Content-Type", "multipart/form-data; boundary =" + boundary); DataOutputStream ds = new DataOutputStream (con. getOutputStream (); ds. writeBytes (twoHyphens + boundary + end); // Upload File Information, including the request parameter name, upload file name, and file type, but not limited to this ds. writeBytes ("Content-Disposition: form-data;" + "name = \" file1 \ "; filename = \" "+ newName +" \ "" + end); ds. writeBytes (end); // get the input stream of the file and transfer the file through the stream. Here I overwrite FileInputStream. To listen to the upload progress, CustomFileInputStream fStream = new CustomFileInputStream (filePath); fStream. setOnUploadListener (listener);/* Set 1024 bytes */int bufferSize = 1024; byte [] buffer = new byte [bufferSize]; int length =-1; // read data from the file to the buffer while (length = fStream. read (buffer ))! =-1) {// write data to ds in DataOutputStream. write (buffer, 0, length);} ds. writeBytes (end); ds. writeBytes (twoHyphens + boundary + twoHyphens + end); fStream. close (); ds. flush (); // obtain the server feedback after the upload is complete. InputStream is = con. getInputStream (); int ch; StringBuffer B = new StringBuffer (); while (ch = is. read ())! =-1) {B. append (char) ch);} ds. close (); return B. toString ();}
CustomFileInputStream. java

Package com. huxq. uploadexample; import java. io. file; import java. io. fileDescriptor; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. IOException; public class CustomFileInputStream extends FileInputStream {private OnUploadListener listener; private int total, done; private double process; public CustomFileInputStream (File file) throws FileNotFoundException {super (file); av Ailable ();} public CustomFileInputStream (FileDescriptor fd) {super (fd); available ();} public CustomFileInputStream (String path) throws FileNotFoundException {super (path ); available () ;}@ Overridepublic int read (byte [] buffer, int byteOffset, int byteCount) throws IOException {done + = byteCount; process = 1.0 * done/total; if (listener! = Null) {listener. onUpload (process);} return super. read (buffer, byteOffset, byteCount);} public void setOnUploadListener (OnUploadListener listener) {this. listener = listener;} @ Overridepublic int available () {try {// get the total size of the file total = super. available ();} catch (IOException e) {e. printStackTrace ();} return total ;}}
OnUploadListener. java

package com.huxq.uploadexample;public interface OnUploadListener {void onUpload(double process);}

Server:

The server receives the file stream through a servlet and writes it to the disk.

Upload. java <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHByZSBjbGFzcz0 = "brush: java;"> package com. huxq. test; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. util. iterator; 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. fileItemFactory; import org. apache. commons. fileupload. fileUploadException; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload;/*** Servlet implementation class Upload */@ WebServlet ("/Upload") public class Upload extends HttpServlet {private static fina L long serialVersionUID = 1L;/*** file storage path */private final String savaPath = "E: \ uploads/";/*** Default constructor. */public Upload () {}/*** @ see HttpServlet # doGet (HttpServletRequest request, response * response) */protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {boolean isMultipart = ServletFileUpload. isMultipartConten T (request); if (isMultipart) {FileItemFactory factory = new DiskFileItemFactory (); ServletFileUpload upload = new ServletFileUpload (factory); List items; try {items = upload. parseRequest (request); Iterator iter = items. iterator (); // you can receive multiple files while (iter. hasNext () {FileItem item = (FileItem) iter. next (); if (item. isFormField () {// common text processing String paramName = item. getFieldName (); String paramValue = item. g EtString (); System. out. println (paramName + ":" + paramValue);} else {// process uploaded file information String fileName = item. getName (); byte [] data = item. get (); String filePath = savaPath + fileName; File file = new File (savaPath); if (! File. exists () {file. mkdirs ();} System. out. println ("filePath:" + filePath); File file2 = new File (filePath); if (file2.exists () file2.delete (); FileOutputStream fos = new FileOutputStream (file2); fos. write (data); fos. close () ;}} response. getWriter (). write ("UPLOAD_SUCCESS");} catch (FileUploadException e) {e. printStackTrace (); response. getWriter (). write ("UPLOAD_FAILED") ;}}/ *** @ see HttpServlet # doPost (HttpServletRequest request, HttpServletResponse * response) */protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}

Here we need two jar packages: commons-fileupload-1.3.1.jar and commons-io-2.4.jar.

All the things you want to talk about are in the Code. If you have any questions, you can download the Demo or leave a message.


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.