我正在尝试在单个请求中上传多个文件。单个文件上传成功,但多个案例怎么办?
这是单文件上传...
public String uploadfile(String sourceFileUri) {
String fileName = "";
File file = null;
String updatedFileName = "";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String HeyfileName = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
// int maxBufferSize = 1 * 1024 * 1024; 5000000
int maxBufferSize = 5000000;
// File sourceFile = sourceFileUri;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
}
File f = new File(sourceFileUri);
File files[] = f.listFiles();
for (int i=0; i < files.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
}
System.out.println("Source file uri is " + sourceFileUri);
if (sourceFileUri.contains(".pdf")) {
fileName = sourceFileUri; /* +"default.jpg" */
long unixTime = System.currentTimeMillis() / 1000L;
fileName = "file:///" + sourceFileUri;
HeyfileName = unixTime + ".pdf";
} else {
MessageDialog.showMessage("Alert!", "Please upload only pdf file!",
User_dashboard.this);
}
try {
InputStream contentInputStream = getContentResolver()
.openInputStream(Uri.parse(fileName));
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
// conn.setRequestProperty("Content-Type", "application/pdf" +
// boundary);
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", HeyfileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"PDF_File\";filename=\""
+ HeyfileName + "\"" + lineEnd);
// dos.writeBytes
// ("Content-Disposition: form-data; name="uploadedfile";filename="" + selectedPath + """
// + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = contentInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = contentInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = contentInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = contentInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Map<String, List<String>> response = conn.getRequestProperties();
// Responses from the server (code and message)
// serverResponseCode = conn.getResponseMessage();
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\n See uploaded file here : \n\n"
* +" http://demo.spearheadss.com/twerck/public/resource/image/"
* +uploadFileName;
*
* messageText.setText(msg); Toast.makeText(UploadToServer.this,
* "File Upload Complete.", Toast.LENGTH_SHORT).show(); } });
*/
}
// close the streams //*/
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
String LogString = "";
while ((inputLine = in.readLine()) != null) {
LogString = LogString + inputLine;
}
responseServer = LogString.toString();
// Log.i(Utils.TAG, LogString);
// close streams
contentInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
pdialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
// messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(User_dashboard.this,
"MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
System.out.println("Error in uploading: " + e);
pdialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
// messageText.setText("Got Exception : see logcat ");
Toast.makeText(User_dashboard.this,
"Uploading failed : please retry",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
pdialog.dismiss();
return responseServer;
// } // End else block
}
但我想上传多个文件,我有一个文件列表
List<String> fileNameList = new ArrayList<String>();
fileNameList .add(file1);
fileNameList .add(file2);
fileNameList .add(file3);
假设文件名如下;
file1 = "/sdcard/selected1.pdf";
file2 = "/sdcard/selected1.pdf";
file3 = "/sdcard/selected1.pdf";
this is giving me exception
InputStream contentInputStream = getContentResolver()
.openInputStream(Uri.parse(myFiles.toString()));
现在我没有得到如何传递fileNameList以便我可以上传它。 有什么办法吗?
答案 0 :(得分:2)
由于您已经有一个发送类,您可以遍历该列表并在时间传递一个文件名?想到这样的事情:
for (String fileName: fileNameList){
uploadFile(fileName);}