如何在android中上传多个文件

时间:2014-10-18 12:25:04

标签: android file-upload

想要上传特定文件夹中的所有文件。从以下代码中保存了数组中的文件列表

String path = Environment.getExternalStorageDirectory().toString()+"/backup/";      
File f = new File(path);        
File file[] = f.listFiles();
int fileNum = file.length;
String[] fileName = new String[fileNum]; 
for (int i=0; i < file.length; i++) {                               
    fileName[i] = file[i].getName();                                
}

我有以下代码上传一个文件。我从哪里循环来自数组fileName的代码,以便它上传该数组中的所有文件

package com.example.uploadfile;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    TextView messageText;
    private Button uploadButton;
    String upLoadServerUri = null;
    int serverResponseCode = 0;

    final String uploadFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/backup/";
    String uploadFileName = "sand.jpg";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        upLoadServerUri = "http://www.example.com/UploadToServer.php";

        messageText = (TextView) findViewById(R.id.messageText);
        uploadButton = (Button) findViewById(R.id.uploadButton);            

        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                new Thread(new Runnable() {
                    public void run() {                     
                        uploadFile(uploadFilePath + "" + uploadFileName);
                    }
                }).start();
            }
        });
    }
    public int uploadFile(String sourceFileUri) {
        String fileName = sourceFileUri;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        try {           
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=" + fileName + "" + lineEnd);
            dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            serverResponseCode = conn.getResponseCode();
            final String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        String msg = "File Upload Completed.\n";
                        msg += "See uploaded file at\n\nhttp://www.example.com/uploads/" + uploadFileName;

                        messageText.setText(msg);
                        Toast.makeText(MainActivity.this, "File Upload Complete:"+serverResponseMessage, Toast.LENGTH_SHORT).show();
                    }
                });
            }           
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (Exception e) {         
            e.printStackTrace();
        }       
        return serverResponseCode;
    }
}

1 个答案:

答案 0 :(得分:2)

  String path = Environment.getExternalStorageDirectory().toString()+"/backup/";      
  File f = new File(path);        
  File file[] = f.listFiles();
  for (int i=0; i < file.length; i++) {                               
      // upload file here and when the fileUpload is complete the you save it to the array.. thats wat i think is best.. because you never know
      //Thread  or asynctask                         
  }

我删除了一些部分。因为我的方式..所以你可以添加它,并绕过它..很希望它有意义