排球 - 如何上传图像文件作为参数

时间:2015-09-20 20:37:44

标签: android android-volley

我在Volley中很新,我想用它来完成我在下面与Postman一样的任务:

Postman Simulation

基本上它是对某个网页的发布请求,其中正文内部有一个名为image的参数,其中包含一个图像文件。

谢谢!

1 个答案:

答案 0 :(得分:0)

以下是您需要的代码。

public class PhotoMultipartRequest<T> extends Request<T> {


private static final String FILE_PART_NAME_1 = "file1";

private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File mImageFile1
protected Map<String, String> headers;

public PhotoMultipartRequest(String url, ErrorListener errorListener, Listener<T> listener, File imageFile1) {
    super(Method.POST, url, errorListener);

    mListener = listener;
    mImageFile1 = imageFile1;


    buildMultipartEntity();
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = super.getHeaders();

    if (headers == null
            || headers.equals(Collections.emptyMap())) {
        headers = new HashMap<String, String>();
    }

    headers.put("test", "multipart/form-data");


    return headers;
}

private void buildMultipartEntity() {
    mBuilder.addBinaryBody(FILE_PART_NAME_1, mImageFile1, ContentType.create("image/jpeg"), mImageFile1.getName());

    mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}

@Override
public String getBodyContentType() {
    String contentTypeHeader = mBuilder.build().getContentType().getValue();
    return contentTypeHeader;
}

@Override
public byte[] getBody() throws AuthFailureError {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        mBuilder.build().writeTo(bos);
    } catch (IOException e) {
        VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
    }

    return bos.toByteArray();
}

@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
    T result = null;
    return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}

@Override
protected void deliverResponse(T response) {
    mListener.onResponse(response);
    }
}