0
我有这个代码,它能够上传JPEG文件到服务器,但该文件不被识别为JPEG。我认为我的问题是关于正确编码JPEG文件。我的解决方案基本上与this one相同。我尝试过使用FileInputStream
添加JPEG字节并使用DataOutputStream
而不是OutputStreamWriter
等尝试其他变体无效。任何建议表示赞赏。Android HttpURLConnection图像上传,但文件不被识别为JPEG
final String boundary = "==================";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter request = null;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
urlConnection.setRequestMethod("POST");
OutputStream outputStream= urlConnection.getOutputStream();
request = new OutputStreamWriter(outputStream);
request.append("--" + boundary).append("\n");
request.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"").append("\n\n");
request.append("Content-Type: " + mimeType).append("\n\n");
request.append("Content-Encoding: base64").append("\n\n");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
//request.append(new String(byteArray)).append("\n");
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
request.append(encodedImage);
request.append("--" + boundary + "--");
request.flush();
request.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString(); // = "Success"
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
'我想我的问题是有关编码JPEG文件correctly.'。什么样的编码?你为什么要编码它?更好地上传文件'原样'。 – greenapps
'OutputStreamWriter request = null;'。你为什么要调用一个输出流编写器'请求'?你用这种方式编写不可读的代码。 – greenapps
'.append(“\ n \ n”);'。你的空行太多了。 – greenapps