2
我想上傳圖像到服務器使用Multipart/form-data,我必須發送一些文字和圖像在同一個電話。當我只發送原始數據時,它工作正常,但是當我添加「圖像上傳部分」時,它不起作用。以下是我的代碼。無法上傳照片使用內容處置android
public String upLoadPostMethod(List<NameValuePair> params, boolean isUploadingPhoto) {
NameValuePair nvp = params.get(1);
String args = nvp.getValue();
System.out.println(args);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "********";
HttpsURLConnection conn;
String response = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String mimeType = "image/jpeg";
try {
URL url = new URL(webServiceUrl);
conn = (HttpsURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
//conn.setChunkedStreamingMode(0);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cookie",
appStatus.getSharedStringValue(appStatus.AUTH_KEY));
System.out.println(appStatus
.getSharedStringValue(appStatus.AUTH_KEY));
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
DataOutputStream dos;
dos = new DataOutputStream(conn.getOutputStream());
// Send parameter #1
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"cmd\""
+ lineEnd + lineEnd);
dos.writeBytes("tsql" + lineEnd);
// Send parameter #2
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"args\""
+ lineEnd + lineEnd);
dos.writeBytes(args + lineEnd);
System.out.println("args======" + args);
if(isUploadingPhoto){
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";"
+"filename=\" 20130125_155208.jpg\"" +"Content-Type: "+mimeType +lineEnd+lineEnd);
FileInputStream fileInputStream = new FileInputStream(Environment.getExternalStorageDirectory().getPath()
+"/20130125_155208.jpg");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
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);
fileInputStream.close();
}else {
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
}
dos.flush();
dos.close();
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine())
response += (inStream.nextLine());
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
有什麼我在這裏做錯了嗎?
我的API工作正常,但有一些問題,圖片上傳部分,我是無法弄清楚。 – abhishek 2013-04-04 14:31:23
哪類問題?你能提供更多的信息嗎?或者是因爲你得到了一些異常或什麼?您認爲上面提供的代碼沒問題。 – 2013-04-05 03:52:39