簡體   English   中英

發布圖像無效的mime類型

[英]posting image Invalid mime type

我試圖從我的galery發布一個圖像從我的Android設備發送到服務器。 他們在后台使用Python。

這就是Back Office開發人員所說的: - Django無法在request.FILES中讀取Android應用程序發布的文件。 iOS正確地做到了這一點 - 似乎Multipart POST沒有正確設置密鑰:正確讀取請求所需的值。

我收到此錯誤:

{“errorMessage”:“”,“message”:“無效的mime類型”,“errorCode”:0,“success”:false}

知道為什么嗎?

這是我的代碼:

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;
 }

我沒有足夠的聲譽來評論,所以我必須把它作為答案。 在你的方法getMultipartEntity()中,第一行:

InputStreamBody isb = new InputStreamBody(fis, mMimeType,  originalPath.getLastPathSegment());

mMimeType的值是多少? 請確保它是正確的mime類型。

這是一個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();
                    }

這是我上傳圖片的代碼。“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;
}

取而代之的MultipartEntity ,我建議你使用MultipartEntityBuilderHttpURLConnection 然后,您可以參考我的以下代碼(注意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();                            
    }
}
...

如果您仍想使用帶有HttpPost MultipartEntityBuilder ,可以參考以下內容:

...
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);
...

您可以發現MultipartEntityBuilder類中的addBinaryBody有許多實現,例如:

  • 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)
  • ...

希望這可以幫助!

我認為這個問題是因為你在代碼中自己設置了Content-Type ,我曾經遇到同樣的問題,我剛剛刪除了Content-Type並且它有效。 如果刪除Content-Type,則表示該庫將根據其類型檢測其Content-Type。

只需刪除此行

httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+"----WebKitFormBoundaryzGJGBFWyGteE24tw");

這是我正在做的,對我來說很好 -

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("photo", new FileBody(new File(imagePath), "image/jpeg"));
httppost.setEntity(entity);

根據這個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");

您可能正在Android 4.0.x上運行代碼,該代碼具有針對multipart / form-data(httpclient)的錯誤實現。 問題已在早些時候報道,並在此處進行了解決

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM