Android排球上传图片

时间:2016-03-04 12:12:37

标签: android android-volley

我正在制作应用,我必须使用Volley上传图片。我试图谷歌,但没有找到类似的东西。使用user_id发布此图片时如何进行多部分图片上传并添加Volley等参数?

在我的情况下,使用Retrofit不是一个选项。

2 个答案:

答案 0 :(得分:0)

首先创建一个文件MultipartRequest,如下所示:

public class MultipartRequest extends Request<String> {
private MultipartEntityBuilder entity = MultipartEntityBuilder.create();
private final Response.Listener<String> mListener;
private final File file;
private final HashMap<String, String> params;

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

    mListener = listener;
    this.file = file;
    this.params = params;
    buildMultipartEntity();
    buildMultipartEntity2();

}



private void buildMultipartEntity()
{
    entity.addBinaryBody(KEY_IMAGE, file, ContentType.create("image/jpeg"), file.getName());
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));

    try
    {
        for ( String key : params.keySet() ) {
            entity.addPart(key, new StringBody(params.get(key)));
        }
    }
    catch (UnsupportedEncodingException e)
    {
        VolleyLog.e("UnsupportedEncodingException");
    }
}

@Override
public String getBodyContentType()
{
    return entity.build().getContentType().getValue();
}
@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("Accept", "application/json");

    return headers;
}

@Override
public byte[] getBody() throws AuthFailureError
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {
        entity.build().writeTo(bos);
    }
    catch (IOException e)
    {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
}
/**
 * copied from Android StringRequest class
 */
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    String parsed;
    try {
        parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    } catch (UnsupportedEncodingException e) {
        parsed = new String(response.data);
    }
    return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}

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

在您的活动中,只需按照以下方式制作多部分请求:

 public void uploadImage()
{
    try {
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading...");
        pDialog.show();

           HashMap params = new HashMap<String, String>();

            params.put(KEY_NAME, name);
        MultipartRequest sr = new MultipartRequest( UPLOAD_URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                if ((pDialog != null) && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                Log.d("file", f + "");
                Log.d("", ".......response====" + response.toString());

                ////////
                try {
                    JSONObject object = new JSONObject(response);
                    String serverCode = object.getString("code");
                    if (serverCode.equalsIgnoreCase("0")) {

                    }
                    if (serverCode.equalsIgnoreCase("1")) {
                        try {

                            if ("1".equals(serverCode)) {
                                JSONObject object1 = object.getJSONObject("data");

                            }
                        }

答案 1 :(得分:0)

使用Retrofit 2:

您需要使用OkHttp的RequestBody类并将您的文件封装到请求正文中(表示您的用户ID)。
1)创建界面

public interface FileUploadService {  
    @Multipart
    @POST("/upload")
    Call<String> upload(
            @Part("myfile\"; filename=\"image.png\" ") RequestBody file,
            @Part("userid") RequestBody userid);
}  

2)活动中的代码:

 FileUploadService service =
            ServiceGenerator.createService(FileUploadService.class);

    String userid = "your_userid";
    RequestBody data =
            RequestBody.create(MediaType.parse("multipart/form-data"), userid);

    File file = new File("path/to/your/file");
    RequestBody requestBody =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);

    Call<String> call = service.upload(requestBody, data);
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            Log.v("Upload", "success");
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            Log.e("Upload", t.getMessage());
        }
    });    

参考链接:https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server