Android : upload Image using MultiPartEntityBuilder

7 篇文章 0 订阅
1 篇文章 0 订阅

I try to upload data to server, my data containing multiple images and large JSON, before it, I Try to send with convert image to string using base64 and send my another data and image that I’ve convert before with JSON, but I face Problem OutOfMemory here, so I read one of solutions that said I must to try using MultipartEntityBuilder. I still confusing and not understand how to do it with MultiPartEntityBuilder, Is there anyone can help me the way to do it with MultiPartEntityBuilder?

To send binary data you need to use addBinaryBody method of MultipartEntityBuilder. Sample of attaching:

import org.apache.http.entity.ContentType; 
import org.apache.http.entity.mime.MultipartEntityBuilder; 
//Image attaching 
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
File file;
multipartEntity.addBinaryBody("someName", file, ContentType.create("image/jpeg"), file.getName()); 
//Json string attaching 
String json;
multipartEntity.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN));

Then make request as usual:

HttpPut put = new HttpPut("url");
put.setEntity(multipartEntity.build());
HttpResponse response = client.execute(put);
int statusCode = response.getStatusLine().getStatusCode();

利用volley时,新建MultipartRequest,如下:


import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.entity.ContentType;
import ch.boye.httpclientandroidlib.entity.mime.HttpMultipartMode;
import ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder;
import com.android.volley.*;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

public class MultipartRequest extends Request<String> {
    private static final String TAG  ="MultipartRequest" ;
    protected static final String PROTOCOL_CHARSET = ResourceUtils.getString(R.string.default_charset);
    // private MultipartEntity entity = new MultipartEntity();

    MultipartEntityBuilder mEntity = MultipartEntityBuilder.create();
    HttpEntity mHttpentity;
    private static final String FILE_PART_NAME = "file";

    private final Response.Listener<String> mListener;
    private final File mFilePart;
    private final Map<String, String> mStringPart;

    public MultipartRequest(String url, Response.ErrorListener errorListener,
                            Response.Listener<String> listener, File file,
                            Map<String, String> mStringPart) {
        super(Method.POST, url, errorListener);

        mListener = listener;
        mFilePart = file;
        if (mFilePart != null) {
            LogCus.d(TAG, "img-path>>" + file.getAbsolutePath());
            LogCus.d(TAG, "img-name>>" + file.getName());
        }
        this.mStringPart = mStringPart;
        mEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        buildMultipartEntity();
    }

    public void addStringBody(String param, String value) {
        if (mStringPart != null) {
            mStringPart.put(param, value);
        } else {
            throw new IllegalArgumentException("创建multipartrequest时并未初始化mStringPart,则不予后期添加数据");
        }
    }

    private void buildMultipartEntity() {
        //NOTE: 1、添加图片
        if (mFilePart != null) {
//            mEntity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
            mEntity.addBinaryBody(FILE_PART_NAME, mFilePart, ContentType.create("image/png"), mFilePart.getName());
        }
        //NOTE: 2、添加字符串部分--转化成utf-8编码
        if (mStringPart != null) {
            for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
                try {
                    mEntity.addBinaryBody(entry.getKey(), entry.getValue().getBytes(PROTOCOL_CHARSET));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public String getBodyContentType() {
        return mHttpentity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            mHttpentity = mEntity.build();
            mHttpentity.writeTo(bos);
        } catch (IOException e) {
            e.printStackTrace();
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
            LogCus.d(TAG, jsonString);
            return Response.success(jsonString, getCacheEntry());
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(String response) {
        mListener.onResponse(response);
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是Android Studio失物招领模块Xml文件的实现代码,请修改代码实现下拉以及图片上传功 <TextView android:id="@+id/shiwuzhaolingzi" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="请选择是失物还是招领" /> <Spinner android:id="@+id/spinner_lost_found" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/lost_found_array" /> <TextView android:id="@+id/text_item_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="物品名称" /> <EditText android:id="@+id/edit_item_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" /> <TextView android:id="@+id/text_item_desc" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="物品描述" /> <EditText android:id="@+id/edit_item_desc" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" /> <TextView android:id="@+id/text_item_time" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="时间" /> <EditText android:id="@+id/edit_item_time" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" /> <TextView android:id="@+id/text_item_location" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="地点" /> <EditText android:id="@+id/edit_item_location" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" /> <Button android:id="@+id/button_upload_image" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="上传图片" /> <TextView android:id="@+id/text_image_path" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="图片路径:" /> <Button android:id="@+id/button_submit" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="提交" /> </LinearLayout>
最新发布
05-17

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值