上传照片时查看进度条

时间:2016-03-27 11:01:27

标签: android file-upload upload progress-bar android-progressbar

请原谅我的英语不是很好, 我得到这段代码可以上传服务器阵列照片, 但我不知道如何用Progress栏显示上传照片的数量, 请帮帮我......

 public class processUpload extends AsyncTask<String ,Integer,JSONObject>{
    String requestURL;
    String charset = "UTF-8";
    JSONObject jsonResponse;
    private File[] files;
    public processUpload(File[] file) {
        this.files = file;
    }
    @Override
    protected void onPreExecute() {
        requestURL = G.DOMEAIN+"/photo";

        pDialog = new ProgressDialog(ActivityUpload.this);
            pDialog.setTitle("Upload Images");
            pDialog.setMessage("pl wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();


    }

    @Override
    protected void onProgressUpdate(Integer... values) {
     //   pDialog.setProgress(values[0]);
    }

    @Override
    protected JSONObject doInBackground(String... params) {

        try {
            final FileUploader multipart = new FileUploader(requestURL, charset);

            multipart.addHeaderField("User-Agent", "CodeJava");
            multipart.addHeaderField("Test-Header", "Header-Value");

            multipart.addFormField("description", "Cool Pictures");
            multipart.addFormField("keywords", "Java,upload,Spring");
            multipart.addFormUserId("userId", UserInfo.USER_ID);


            for (int i = 0; i < G.selectImages.size(); i++) {

                    multipart.addFilePart("images[]", sourceFile[i]);

            }


        /*multipart.addFilePart("fileUpload", uploadFile1);
        multipart.addFilePart("fileUpload", uploadFile2);*/

            List<String> response = multipart.finish();

            System.out.println("SERVER REPLIED:");

            for (String line : response) {
                System.out.println(line);
            }
            jsonResponse = new JSONObject(response.get(0));

        } catch (IOException ex) {
            System.err.println(ex);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonResponse;
    }

    @Override
    protected void onPostExecute(JSONObject json) {
            //do something
        }

    }
}

和这个FileUploader类

 public class FileUploader {
    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;

    public FileUploader(String requestURL, String charset)
            throws IOException {
        this.charset = charset;

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
        httpConn.setRequestProperty("Test", "Bonjour");
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);


    }       
   /**
     * Adds a form field to the request
     * @param name field name
     * @param value field value
     */
    public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }
    /**
     * Adds a form field to the request
     * @param name field name
     * @param value field value
     */
    public void addFormUserId(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a upload file section to the request
     * @param fieldName name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName
                        + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);

        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        int totalByteRead = 0;


        int n=1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            totalByteRead += bytesRead;
            outputStream.write(buffer, 0, bytesRead);

        }
        outputStream.flush();
        inputStream.close();

        writer.append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a header field to the request.
     * @param name - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Completes the request and receives response from the server.
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public List<String> finish() throws IOException {
        List<String> response = new ArrayList<String>();

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.add(line);
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response;
    }
}

1 个答案:

答案 0 :(得分:0)

检查以下代码以进行文件上传

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

 final static int REQUEST_CODE = 1;
 final static String[]BUTTON_LABEL = {"Select Image","Upload Image"};

 // CHANGE THIS TO YOUR URL
 final static String UPLOAD_SERVER_URI = "http://192.168.25.117/android/UploadToServer.php";

 ProgressDialog progressDialog;
 ScrollView scrollView;
 LinearLayout linearLayout;
 ImageView imageView;
 TextView  imageLocationTextView;
 Button selectImgBtn;
 Button uploadBtn;

 String imagePath;
 String imageName;

 long imageSize = 0; // kb

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setupLayout();
    }
    /**
     * 
     */
    private void setupLayout(){

     scrollView = new ScrollView(this);
     linearLayout = new LinearLayout(this);
     imageView = new ImageView(this);
     imageLocationTextView = new TextView(this);
     selectImgBtn = new Button(this);
     uploadBtn = new Button(this);


     selectImgBtn.setText(BUTTON_LABEL[0]);
     uploadBtn.setText(BUTTON_LABEL[1]);
     selectImgBtn.setOnClickListener(this);
     uploadBtn.setOnClickListener(this);

     linearLayout.setOrientation(LinearLayout.VERTICAL);
     linearLayout.addView(imageView);
     linearLayout.addView(imageLocationTextView);
     linearLayout.addView(selectImgBtn);
     linearLayout.addView(uploadBtn);

     scrollView.addView(linearLayout);

     this.setContentView(scrollView);
    }
    /**
     * 
     * @return
     */
    private ProgressDialog createDialog(){
     ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Please wait.. Uploading File");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);

        return progressDialog;
    }

 @Override
 public void onClick(View view) {

  String viewLabel = ((Button)view).getText().toString();

  if(viewLabel.equalsIgnoreCase(BUTTON_LABEL[0])){
   // SELECT IMAGE

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_CODE);

  }else{

   // UPLOAD IMAGE

   if(this.imagePath == null){
    // IF NO IMAGE SELECTED DO NOTHING
    Toast.makeText(this, "No image selected", Toast.LENGTH_SHORT).show();
    return;
   }

   this.progressDialog = this.createDialog();
   this.progressDialog.show();

   // EXECUTED ASYNCTASK TO UPLOAD IMAGE
   new ImageUploader().execute();

  }

 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  super.onActivityResult(requestCode, resultCode, data);

  if(requestCode == REQUEST_CODE && resultCode == RESULT_OK){

   Uri selectedImageUri = data.getData();

   // GET IMAGE PATH
   imagePath = getPath(selectedImageUri);


   // IMAGE NAME
   imageName = imagePath.substring(imagePath.lastIndexOf("/"));

   imageSize = this.getFileSize(imagePath);

   // DECODE TO BITMAP
   Bitmap bitmap=BitmapFactory.decodeFile(imagePath);

   // DISPLAY IMAGE
   imageView.setImageBitmap(bitmap);
   imageLocationTextView.setText("File path :" +imagePath);

  }
 }

 /**
  * Get the image path
  * @param uri
  * @return
  */
 private String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
 /**
  * Get the file size in kilobytes
  * @return
  */
 private long getFileSize(String imagePath){

   long length = 0;

  try {

   File file = new File(imagePath);
   length = file.length();
   length = length / 1024;

  } catch (Exception e) {

   e.printStackTrace();
  }

  return length;
 }

 /**
  * This class is responsible for uploading data
  * @author lauro
  *
  */
  private class ImageUploader extends AsyncTask<Void, Integer, Boolean> implements UploadProgressListener {

   @Override
   protected Boolean doInBackground(Void... params) {

          try{

             InputStream inputStream = new FileInputStream(new File(imagePath));

              //*** CONVERT INPUTSTREAM TO BYTE ARRAY

              byte[] data = this.convertToByteArray(inputStream);

              HttpClient httpClient = new DefaultHttpClient();
              httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,System.getProperty("http.agent"));

              HttpPost httpPost = new HttpPost(UPLOAD_SERVER_URI);

              // STRING DATA
              StringBody dataString = new StringBody("This is the sample image");

              // FILE DATA OR IMAGE DATA
              InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data),imageName);

             // MultipartEntity multipartEntity = new MultipartEntity();
              CustomMultiPartEntity  multipartEntity = new CustomMultiPartEntity();

              // SET UPLOAD LISTENER
              multipartEntity.setUploadProgressListener(this);

              //*** ADD THE FILE
              multipartEntity.addPart("file", inputStreamBody);

              //*** ADD STRING DATA
              multipartEntity.addPart("description",dataString);   

              httpPost.setEntity(multipartEntity);

              // EXECUTE HTTPPOST
              HttpResponse httpResponse = httpClient.execute(httpPost);

              // THE RESPONSE FROM SERVER
              String stringResponse =  EntityUtils.toString(httpResponse.getEntity());

              // DISPLAY RESPONSE OF THE SERVER
              Log.d("data from server",stringResponse);



          } catch (FileNotFoundException e1) {
              e1.printStackTrace();

              return false;

          } catch (ClientProtocolException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();

     return false;

    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();

     return false;
    }

     return true;
   }

   /**
    * 
    */
   @Override
   public void transferred(long num) {

    // COMPUTE DATA UPLOADED BY PERCENT

    long dataUploaded = ((num / 1024) * 100 ) / imageSize;

    // PUBLISH PROGRESS

    this.publishProgress((int)dataUploaded);

   }

   /**
    * Convert the InputStream to byte[]
    * @param inputStream
    * @return
    * @throws IOException
    */
   private byte[] convertToByteArray(InputStream inputStream) throws IOException{

         ByteArrayOutputStream bos = new ByteArrayOutputStream();

         int next = inputStream.read();
         while (next > -1) {
               bos.write(next);
               next = inputStream.read();
          }

         bos.flush();

         return bos.toByteArray();
   }



   @Override
   protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);

    // UPDATE THE PROGRESS DIALOG

    progressDialog.setProgress(values[0]);



   }

   @Override
   protected void onPostExecute(Boolean uploaded) {
    // TODO Auto-generated method stub
    super.onPostExecute(uploaded);


    if( uploaded){

     // UPLOADING DATA SUCCESS

     progressDialog.dismiss();
     Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();


    }else{

     // UPLOADING DATA FAILED

     progressDialog.setMessage("Uploading Failed");
     progressDialog.setCancelable(true);


    }


   }



  }


}

有关详情,请点击以下链接。

http://justsimpleinfo.blogspot.in/2014/07/android-upload-file-to-server-with-data.html

希望它对您有所帮助。

相关问题