Android and android Official Website

Source: Internet
Author: User

Android and android Official Website

Background

I have uploaded a lot of files to the java server on the Internet for a long time and found the files to be uploaded to php. The idea is similar to what I originally thought, that is, POST. Look at the code.

Php code

<? Php $ target_path = ". /upload/"; // Receiving File directory $ target_path = $ target_path. basename ($ _ FILES ['uploadfile'] ['name']); if (move_uploaded_file ($ _ FILES ['uploadfile'] ['tmp _ name'], $ target_path) {echo "The file ". basename ($ _ FILES ['uploadfile'] ['name']). "has been uploaded";} else {echo "There was an error uploading the file, please try again! ". $ _ FILES ['uploadfile'] ['error'];}?>

Android code

Main upload code:

Private void uploadFile (String uploadUrl) {String end = "\ r \ n"; String twoHyphens = "--"; String boundary = "******"; try {URL url = new URL (uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url. openConnection (); // http connection // you can specify the stream size for each transmission, this method can effectively prevent the phone from crashing due to insufficient memory // This method is used to enable the stream of HTTP Request body without internal buffering when the content length is unknown in advance. HttpURLConnection. setChunkedStreamingMode (128*1024); // 128 K // allow the input/output stream httpURLConnection. setDoInput (true); httpURLConnection. setDoOutput (true); httpURLConnection. setUseCaches (false); // use the POST method httpURLConnection. setRequestMethod ("POST"); httpURLConnection. setRequestProperty ("Connection", "Keep-Alive"); // Keep connected to httpURLConnection. setRequestProperty ("Charset", "UTF-8"); // code httpURLConnection. setRe QuestProperty ("Content-Type", "multipart/form-data; boundary =" + boundary); // POST transmits the previous encoding DataOutputStream dos = new DataOutputStream (httpURLConnection. getOutputStream (); // output stream dos. writeBytes (twoHyphens + boundary + end); dos. writeBytes ("Content-Disposition: form-data; name = \" uploadedfile \ "; filename = \" "+ srcPath. substring (srcPath. lastIndexOf ("/") + 1) + "\" "+ end); dos. writeBytes (end); FileInput Stream FD = new FileInputStream (srcPath); // file input Stream, written to the memory byte [] buffer = new byte [8192]; // 8 k int count = 0; // read the file while (count = Fi. read (buffer ))! =-1) {dos. write (buffer, 0, count);} FD. close (); dos. writeBytes (end); dos. writeBytes (twoHyphens + boundary + twoHyphens + end); dos. flush (); InputStream is = httpURLConnection. getInputStream (); // http input. The returned result is InputStreamReader isr = new InputStreamReader (is, "UTF-8"); BufferedReader br = new BufferedReader (isr); String result = br. readLine (); Toast. makeText (this, result, Toast. LENGTH_LONG ). show (); // output the result to dos. close (); is. close ();} catch (Exception e) {e. printStackTrace (); setTitle (e. getMessage ());}}

Because the time-consuming operations after Android 4.0 are required to be performed in non-UI threads, I will use the previous AsyncTask ~

AsyncTask Portal: http://www.cnblogs.com/yydcdut/p/3707960.html

In this class, put the upload operation in doInBackground, and you can see ProgressDialog to display the upload quantity:

// Read file            bytesRead = fileInputStream.read(buffer, 0, bufferSize);            while (bytesRead > 0) {                outputStream.write(buffer, 0, bufferSize);                length += bufferSize;                progress = (int) ((length * 100) / totalSize);                publishProgress(progress);                bytesAvailable = fileInputStream.available();                bufferSize = Math.min(bytesAvailable, maxBufferSize);                bytesRead = fileInputStream.read(buffer, 0, bufferSize);            }            outputStream.writeBytes(lineEnd);            outputStream.writeBytes(twoHyphens + boundary + twoHyphens                    + lineEnd);            publishProgress(100);

Also, pay attention to the permissions:

<uses-permission android:name="android.permission.INTERNET" />

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.