开发者

How to upload image through multipartform data to server (Android)

开发者 https://www.devze.com 2023-03-29 05:34 出处:网络
开发者_如何学编程I want to upload image to a server. URL: http://asptest.expenseanywhere.com/eamobile/imageupload.aspx

开发者_如何学编程I want to upload image to a server. URL:

http://asptest.expenseanywhere.com/eamobile/imageupload.aspx

Server requirer 5 fields for getting the response of successful upload that are: corporate id, username, password, etc. and image also. So how to send all these data to server and upload the image to server successfully? Please reply in details because I am new in Android and Java and I am not getting the idea how to do that. I am reading this article:

http://http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html

but in this article only the image is sent to server. So how to write all the fields which I want to file and send all the fields to server for uploading the image? Help would be greatly appreciated.


I've used this to post form data, it might work for you:

    final HttpUriRequest http_request = new HttpPost(url);
    final List<NameValuePair> form_params = new ArrayList<NameValuePair>();
    form_params.add(new BasicNameValuePair("key1", value1));                
    form_params.add(new BasicNameValuePair("key2", value2));                
    form_params.add(new BasicNameValuePair("key3", value3));                
    try {
        ((HttpPost) http_request).setEntity(new UrlEncodedFormEntity(form_params));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    http_request.setHeader("Content-Type", "application/x-www-form-urlencoded");

then use an DefaultHttpClient with this request.


You have to upload it as a byte array. Check out how its done in this blog I found:

http://vikaskanani.wordpress.com/2011/01/29/android-image-upload-activity/

Heres the part your looking for here:

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);

            byte[] data = bos.toByteArray();
            entity.addPart("photoId", new StringBody(getIntent()
                    .getStringExtra("photoId")));
           entity.addPart("returnformat", new StringBody("json"));

            entity.addPart("uploaded", new ByteArrayBody(data,
                    "myImage.jpg"));
            entity.addPart("photoCaption", new StringBody(caption.getText()
                    .toString()));
0

精彩评论

暂无评论...
验证码 换一张
取 消