简体   繁体   中英

Upload Image in JPEG format from Android through POST

I am trying to use Google Image search to upload an image programmaticaly (android) and parse the result. I am continuously getting the error - "The image must be in one of the following formats: .jpg, .gif, .png, .bmp, .tif, or .webp."

It works fine when doing the same thing from a browser. I compared the two requests through fiddler and both of them look similar as far as Content-Type is concerned:

Content-Type: multipart/form-data; boundary=A3EwwOwLJr168nlq1CZSlVUuQ1m5X9W

--A3EwwOwLJr168nlq1CZSlVUuQ1m5X9W
Content-Disposition: form-data; name="file"; filename="File_1390748740620.jpeg"
Content-Type: image/jpeg

I am not able to figure out what the issue might be. Please guide. The code is as follows (I tried two approaches, both of them in the code):

// Approach 1:
//  ByteArrayOutputStream bos = new ByteArrayOutputStream();
//  Bitmap bitmap = BitmapFactory.decodeFile(fileName);
//  bitmap.compress(CompressFormat.JPEG, 100, bos);
//  byte[] data = bos.toByteArray();
//  ByteArrayBody bab = new ByteArrayBody(data, "image/jpeg", fileName);

// Approach 2:      
File file = new File(fileName);
ContentBody cbFile = new FileBody(file, "image/jpeg");

MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", cbFile);

HttpPost post = new HttpPost(uploadUrl);
post.setEntity(reqEntity);

Here is exactly what you want.

HttpRequestWithEntity.java

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

public class HttpRequestWithEntity extends HttpEntityEnclosingRequestBase {

    private String method;

    public HttpRequestWithEntity(String url, String method) {
        if (method == null || (method != null && method.isEmpty())) {
            this.method = HttpMethod.GET;
        } else {
            this.method = method;
        }
        try {
            setURI(new URI(url));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getMethod() {
        return this.method;
    }

}

And here if you want to upload photo or video and you can show progressbar if you want.

public static class UploadPhoto extends AsyncTask<String, Void, InputStream> {
    private static final String TAG = "UploadImage";
    byte[] buffer;
    byte[] data;
    //private long dataLength = 0;
    private INotifyProgressBar iNotifyProgressBar;
    private int user_id;
    private IAddNewItemOnGridView mAddNewItemOnGridView;
    public UploadPhoto(INotifyProgressBar iNotifyProgressBar, 
            IAddNewItemOnGridView mAddNewItemOnGridView, int user_id) {
        this.iNotifyProgressBar = iNotifyProgressBar;
        this.user_id = user_id;
        this.mAddNewItemOnGridView = mAddNewItemOnGridView;
    }

    @Override
    protected InputStream doInBackground(String... names) {
        File mFile = null;
        FileBody mBody = null;
        File dcimDir = null;
        try {
            String fileName = names[0];
            dcimDir = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
            mFile = new File(dcimDir, Def.PHOTO_TEMP_DIR + fileName);
            if (!mFile.isFile()) {
                iNotifyProgressBar.notify(0, UploadStatus.FAILED);
                return null;
            }
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(Def.BASE_URL 
                    + String.format("/%d/list", this.user_id));
            final int maxBufferSize = 10 * 1024;
            mBody = new FileBody(mFile, fileName, "image/jpeg", "UTF-8"){
                int bytesRead, bytesAvailable, bufferSize;
                InputStream mInputStream = super.getInputStream();
                int dataLength = mInputStream.available();
                @Override
                public void writeTo(OutputStream out) throws IOException {
                    bytesAvailable = mInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];
                    bytesRead = mInputStream.read(buffer, 0, bufferSize);
                    while (bytesRead > 0) {
                        out.write(buffer, 0, bufferSize);
                        bytesAvailable = mInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = mInputStream.read(buffer, 0, bufferSize);
                        int progress = (int) (100 - ((bytesAvailable * 1.0) / dataLength) * 100);
                        Log.d(TAG, "Result: " + progress + "%");
                        if (progress == 100) {
                            iNotifyProgressBar.notify(progress, UploadStatus.SUCCESS);
                        } else {
                            iNotifyProgressBar.notify(progress, UploadStatus.UPLOADING);
                        }
                    }
                }
                @Override
                protected void finalize() throws Throwable {
                    super.finalize();
                    if (mInputStream != null) {
                        mInputStream.close();
                    }
                }   
            };

            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);              
            reqEntity.addPart("photo", mBody);
            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            InputStream mInputStream = response.getEntity().getContent();
            return mInputStream == null ? null : mInputStream;
        } catch (IOException e) {
            Log.e(TAG, "Error causes during upload image: " + e.getMessage());
            e.printStackTrace();
            iNotifyProgressBar.notify(0, UploadStatus.FAILED);
        } finally {
            Log.v(TAG, "Close file");
            if (mFile != null) {
                mFile = null;
            }
            if (mBody != null) {
                mBody = null;
            }
            if (dcimDir != null) {
                dcimDir = null;
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(InputStream result) {
        if (result == null) {
            iNotifyProgressBar.notify(0, UploadStatus.FAILED);
        } else {
            PhotoInfo mPhotoInfo = ApiUtils.convertStreamToPhotoInfo(result);
            if (mAddNewItemOnGridView != null && mPhotoInfo != null) {
                mAddNewItemOnGridView.notifyAdded(mPhotoInfo);
                Log.d(TAG, "Upload completed!!");
            } else {
                Log.d(TAG, "Upload is failed!!");
                iNotifyProgressBar.notify(0, UploadStatus.FAILED);
            }
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM