我正在尝试将我的galery中的图像从我的Android设备发布到服务器。 他们在后台使用Python。
这就是后台开发人员所说的: - Django无法在request.FILES中读取Android应用发布的文件。 iOS正确地做到了这一点 - 似乎Multipart POST没有正确设置密钥:正确读取请求所需的值。
我收到此错误:
{“errorMessage”:“”,“message”:“无效的mime 类型”, “错误码”:0, “成功”:假}
知道为什么吗?
这是我的代码:
public static final String IMAGE_JPEG = "image/jpeg";
private HttpEntity getImageEntity() throws Exception {
File imageFile;
Uri originalUri = Uri.parse(this.mFileName);
String originalPath = originalUri.getPath();
boolean isEncrypted = originalPath.contains(FileNames.CACHE_DIR.getPath());
// check if file encrypted or not
if (isEncrypted && ImageLoader.IMAGE_CODING_ENABLED) {
File originalImageFile = new File(originalPath);
String decodedPath = CipherUtils.decryptFile(SmartPagerApplication.getInstance(), originalImageFile);
imageFile = new File(decodedPath);
} else {
imageFile = new File(originalPath);
}
InputStream fis = imageFile.toURI().toURL().openStream();
int rotation = PhotoFileUtils.getOrientation(this.mFileName);
if (rotation > 0) {
byte[] data;
Bitmap rotateBitmap = PhotoFileUtils.checkOrientation(BitmapFactory.decodeStream(fis), rotation);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
rotateBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
data = stream.toByteArray();
stream.close();
rotateBitmap.recycle();
fis.close();
fis = new ByteArrayInputStream(data);
} else {
// data = IOUtils.toByteArray(fis);
}
return getMultipartEntity(originalUri, fis);
}
private MultipartEntity getMultipartEntity(Uri originalPath, InputStream fis) {
InputStreamBody isb = new InputStreamBody(fis, mMimeType, originalPath.getLastPathSegment());
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
"----WebKitFormBoundaryzGJGBFWyGteE24tw", Charset.forName("ISO-8859-1"));
multipartEntity.addPart("binaryFile", isb);
return multipartEntity;
}
private String executePost(String url, HttpEntity params) throws ClientProtocolException, IOException {
Log.e("executePost url =" + url);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+"----WebKitFormBoundaryzGJGBFWyGteE24tw");
httpPost.addHeader("Cache-Control", "no-cache");
httpPost.setEntity(params);
String response = SmartPagerHTTPClient.getHttpClient().execute(httpPost, new BasicResponseHandler());
return response;
}
答案 0 :(得分:3)
我没有足够的声誉来评论,所以我必须把它作为答案。在你的方法getMultipartEntity()中,第一行:
InputStreamBody isb = new InputStreamBody(fis, mMimeType, originalPath.getLastPathSegment());
mMimeType的值是多少?请确保它是正确的mime类型。
答案 1 :(得分:2)
这是一个OKHttp实现
首先,您需要将其包含在依赖项中:
compile 'com.squareup.okhttp:okhttp:2.4.0'
实际上传代码:在Asynctask中调用
File upload;
upload = new File("<<Your Path to image>>");
Response response;
String finalResponce;
try {
RequestBody body = new MultipartBuilder()
.addFormDataPart("Image", upload.getName(), RequestBody.create(MediaType.parse("image/jpeg"), upload))
.build();
Request request = new Request.Builder()
.url("https://iamin-events.appspot.com/UploadServlet")
.post(body)
.build();
response = new OkHttpClient().newCall(request).execute();
finalResponce = response.body().string();
finalResponce = finalResponce.trim();
mainEventListing.setBackdropUrl(finalResponce);
} catch (Exception e) {
// show error
e.printStackTrace();
}
答案 2 :(得分:0)
这是我上传图片的代码。“Content-Type”就像httpConnection.setRequestProperty(“Content-Type”,“image / jpeg”);
public String doPutUploadImage(File image) throws Exception {
String imageUrl = "http://" + Const.BUCKET_NAME
+ ".oss-cn-hangzhou.aliyuncs.com/" + image.getName();
URL localURL = new URL(imageUrl);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("PUT");
httpConnection.setRequestProperty("Host",
Const.BUCKET_NAME.concat(".oss-cn-hangzhou.aliyuncs.com"));
String GMTDate = SignatureMaker.getGMTDate();
if(!GMTDate.contains("+")){
httpConnection.setRequestProperty("Date", GMTDate);
}else{
GMTDate=GMTDate.substring(0, GMTDate.indexOf("+"));
httpConnection.setRequestProperty("Date", GMTDate);
}
httpConnection.setRequestProperty("Content-Encoding", "UTF-8");
httpConnection.setRequestProperty("Content-Type", "image/jpeg");
httpConnection.setRequestProperty("Content-Length",
String.valueOf(image.length()));
httpConnection.setRequestProperty("Authorization",
"OSS "+ ACCESS_ID+ ":"
+ SignatureMaker.makeSignature(ACCESS_KEY, "PUT",
Const.BUCKET_NAME, image, GMTDate));
sendRequest(httpConnection, image);
return imageUrl;
}
答案 3 :(得分:0)
我建议您将MultipartEntity
与MultipartEntityBuilder
一起使用,而不是HttpURLConnection
。然后,您可以参考我的以下代码(注意ContentType contentType = ContentType.create("image/jpeg");
):
...
byte[] bitmapData = byteArrayOutputStream.toByteArray();
String address = "http://192.168.1.100/api/postfile";
String boundary = "----apiclient----" + System.currentTimeMillis();
String mimeType = "multipart/form-data;boundary=" + boundary;
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.setBoundary(boundary);
// Add binary body
if (bitmapData != null) {
ContentType contentType = ContentType.create("image/jpeg"); //CREATE ContentType for the file part
String fileName = "some_file_name.jpeg";
entityBuilder.addBinaryBody("binaryFile", bitmapData, contentType, fileName);
try {
URL url = new URL(address);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", mimeType);
entityBuilder.build().writeTo(urlConnection.getOutputStream());
JSONObject jsonObject = new JSONObject();
try {
if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
// process urlConnection.getInputStream();
} else {
// process urlConnection.getErrorStream();
}
jsonObject.put("Message", urlConnection.getResponseMessage());
jsonObject.put("Length", urlConnection.getContentLength());
jsonObject.put("Type", urlConnection.getContentType());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
...
如果您仍想将MultipartEntityBuilder
与 HttpPost
一起使用,可以参考以下内容:
...
byte[] bytes = byteArrayOutputStream.toByteArray();
ContentType contentType = ContentType.create("image/jpeg");
String fileName = "some_filename.jpg";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// Add binary body
builder.addBinaryBody("binaryFile", bytes, contentType, fileName);
HttpEntity httpEntity = builder.build();
httpPost.setEntity(httpEntity);
...
您可以发现 addBinaryBody
类中的 MultipartEntityBuilder
有许多实现,例如:
- public MultipartEntityBuilder addBinaryBody(String name,InputStream stream,ContentType contentType,String filename)
- public MultipartEntityBuilder addBinaryBody(String name,File file,ContentType contentType,String filename)
- public MultipartEntityBuilder addBinaryBody(String name,byte [] b,ContentType contentType,String filename)
- ...
希望这有帮助!
答案 4 :(得分:0)
我认为这个问题是因为您在代码中设置了内容类型,我曾经遇到同样的问题我刚刚删除了 Content-Type 和它工作。如果您删除了内容类型,则表示该库将根据其类型检测其内容类型。
只需删除此行
即可httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+"----WebKitFormBoundaryzGJGBFWyGteE24tw");
答案 5 :(得分:0)
这就是我正在做的事情并且对我有用 -
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("photo", new FileBody(new File(imagePath), "image/jpeg"));
httppost.setEntity(entity);
答案 6 :(得分:0)
根据此org.apache.http文档更改您的mime类型静态声明
public static final String IMAGE_JPEG = "image/jpeg";
到
public static final String IMAGE_JPEG = "image/png";
除了@BNK答案而不是MultipartEntity,您可以将MultipartEntityBuilder与HttpURLConnection一起使用。您可以将图像作为二进制体上传,然后您可以设置类型和名称:
multiPartEntityBuilder.addBinaryBody(imageName, byteArray, ContentType.create("image/png"), "image.png");
答案 7 :(得分:0)