在我的应用程序中,我需要在服务器上使用字符串值上传图像。
以下是我用来实现此目的的代码: -
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(url_profile_path);
// 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",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
conn.setRequestProperty("unique_id", String.valueOf(Globals.list_user.get(0).id));
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
// create a buffer of maximum size
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);
}
// send multipart form data necesssary after file data...
dos.writeBytes("Content-Disposition: form-data; name=\"unique_id\";String.valueOf(Globals.list_user.get(0).id)=\""
+ String.valueOf(Globals.list_user.get(0).id) + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
InputStream in = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
StringBuilder response = new StringBuilder();
char[] b = new char[512];
int read;
while ((read = bufferedReader.read(b)) != -1) {
response.append(b, 0, read);
}
Log.d("MultipartServer", response.toString());
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
使用此代码图片可以完美上传,但不会发送标记为' unique_id'的其他参数。其值为' String.valueOf(Globals.list_user.get(0).id)'。
有人请解释我应该怎样做才能实现它? 提前谢谢。