Android method for uploading files

  • 2020-06-03 08:13:51
  • OfStack

This article describes the source code of an Android upload file. Each step of the implementation process is equipped with detailed comments, so the idea is relatively clear. After learning the upload file code described in this example, you can handle the upload of other files in other formats. In the example, the main method to upload files to Server is implemented, which allows Input and Output to upload files without using Cache, making it easy for Androiod to upload files.

The main function codes are as follows:


package com.test;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
  /*  Variable declarations 
  * newName : The name of the file uploaded on the server 
  * uploadFile : The path to the file to upload 
  * actionUrl : The corresponding program path on the server  */
  private String newName="image.jpg";
  private String uploadFile="/data/image.jpg";
  private String actionUrl="http://l27.0.0.1/upload/upload.jsp";
  private TextView mText1;
  private TextView mText2;
  private Button mButton;

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   mText1 = (TextView) findViewById(R.id.myText2);
   mText1.setText(" File path: \n"+uploadFile);
   mText2 = (TextView) findViewById(R.id.myText3);
   mText2.setText(" Upload site: \n"+actionUrl);
   /*  Set up the mButton the onClick The event processing  */  
   mButton = (Button) findViewById(R.id.myButton);
   mButton.setOnClickListener(new View.OnClickListener()
   {
    public void onClick(View v)
    {
     uploadFile();
    }
   });
  }

  /*  Upload file to Server The method of  */
  private void uploadFile()
  {
   String end = "\r\n";
   String twoHyphens = "--";
   String boundary = "*****";
   try
   {
    URL url =new URL(actionUrl);
    HttpURLConnection con=(HttpURLConnection)url.openConnection();
    /*  allow Input , Output And don't use Cache */
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    /*  Set transmitted method=POST */
    con.setRequestMethod("POST");
    /* setRequestProperty */
    con.setRequestProperty("Connection", "Keep-Alive");
    con.setRequestProperty("Charset", "UTF-8");
    con.setRequestProperty("Content-Type",
             "multipart/form-data;boundary="+boundary);
    /*  Set up the DataOutputStream */
    DataOutputStream ds = 
     new DataOutputStream(con.getOutputStream());
    ds.writeBytes(twoHyphens + boundary + end);
    ds.writeBytes("Content-Disposition: form-data; " +
           "name=\"file1\";filename=\"" +
           newName +"\"" + end);
    ds.writeBytes(end);  

    /*  Retrievable FileInputStream */
    FileInputStream fStream = new FileInputStream(uploadFile);
    /*  Set each write 1024bytes */
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];

    int length = -1;
    /*  Reads data from the file to the buffer  */
    while((length = fStream.read(buffer)) != -1)
    {
     /*  Write data to DataOutputStream In the  */
     ds.write(buffer, 0, length);
    }
    ds.writeBytes(end);
    ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

    /* close streams */
    fStream.close();
    ds.flush();

    /*  achieve Response content  */
    InputStream is = con.getInputStream();
    int ch;
    StringBuffer b =new StringBuffer();
    while( ( ch = is.read() ) != -1 )
    {
     b.append( (char)ch );
    }
    /*  will Response Shown in Dialog */
    showDialog(b.toString().trim());
    /*  Shut down DataOutputStream */
    ds.close();
   }
   catch(Exception e)
   {
    showDialog(""+e);
   }
  }

  /*  According to Dialog the method */
  private void showDialog(String mess)
  {
   new AlertDialog.Builder(Main.this).setTitle("Message")
   .setMessage(mess)
   .setNegativeButton(" determine ",new DialogInterface.OnClickListener()
   {
    public void onClick(DialogInterface dialog, int which)
    {     
    }
   })
   .show();
  }
}

If the reader feels that the function is insufficient, the code can be extended and improved to make it more suitable for their own application requirements.


Related articles: