如何使用Android中的Volley库上传文件?

时间:2022-01-05 08:22:44

I already have a sub class of Request that is used for http post to the server. The problem is, I have no idea on how can I add a parameter for a file. Posting string to the server is easy. but I need to add file as a different parameter. How can I do it?

我已经有一个Request子类用于http发送到服务器。问题是,我不知道如何为文件添加参数。将字符串发布到服务器很容易。但我需要将文件添加为不同的参数。我该怎么做?

public class AddNewPetRequest extends Request<JSONObject> {

    private Response.Listener<JSONObject> listener;

    public AddNewPetRequest(String url, Map<String, String> params,
                                Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
        super(Request.Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public AddNewPetRequest(int method, String url, Map<String, String> params,
                                Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

UPDATE QUESTION: I follow the pattern of one of the answers here in * and I came up with this implementation:

更新问题:我在*中遵循其中一个答案的模式,我想出了这个实现:

public class MultipartRequest extends Request<String> {

private MultipartEntity entity = new MultipartEntity();

private final Response.Listener<String> mListener;
private HashMap<String, String> mParams;


public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener)
{
    super(Method.POST, url, errorListener);
    mListener = listener;

    buildMultipartEntity();
}

private void buildMultipartEntity()
{
    entity.addPart("profile_picture", new FileBody(new File("/storage/emulated/0/Pictures/VSCOCam/2015-07-31 11.55.14 1.jpg")));
    try
    {
        entity.addPart("user_id", new StringBody("15"));
        entity.addPart("name", new StringBody("Bogs"));
        entity.addPart("gender", new StringBody("Male"));
        entity.addPart("date_birth", new StringBody("1999-12-5"));
        entity.addPart("breed", new StringBody("monkey"));
    }
    catch (UnsupportedEncodingException e)
    {
        VolleyLog.e("UnsupportedEncodingException");
    }
}

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

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

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
    return Response.success("Uploaded", getCacheEntry());
}

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

}

When I add this request to my request queue, it respond a com.android.volley.TimeoutError but if a check the data base, the request executes and add items to the table but the profile picture upload has only 1 byte of size. another problem, my database item added twice.

当我将此请求添加到我的请求队列时,它会响应com.android.volley.TimeoutError但是如果检查数据库,请求会执行并向表中添加项目,但是配置文件图片上载只有1个字节的大小。另一个问题,我的数据库项添加了两次。

PROBLEM SOLVED I already fixed this by setting its request time. what was happened is I am not able to get the response from my server after the default timeout of volley library so set my timeout by calling and setting this method to my Request Queue:

问题已解决我已经通过设置其请求时间来解决这个问题。发生的事情是我无法在凌空库的默认超时后从我的服务器获得响应,因此通过调用并将此方法设置为我的请求队列来设置我的超时:

multipartRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 60, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

1 个解决方案

#1


8  

I have commented but perhaps you haven't read yet. So here is my answer.

我评论过,但也许你还没有读过。所以这是我的答案。

If you want to use Volley, you can refer to some following links:

如果您想使用Volley,可以参考以下链接:

  1. Working POST Multipart Request with Volley and without HttpEntity
  2. 使用Volley和没有HttpEntity工作POST多部分请求
  3. How to send a “multipart/form-data” POST in Android with Volley
  4. 如何使用Volley在Android中发送“multipart / form-data”POST
  5. Trouble Sending Multipart File with Boundary via Volley
  6. 无法通过Volley发送带有边界的多部分文件

Hope this helps

希望这可以帮助

#1


8  

I have commented but perhaps you haven't read yet. So here is my answer.

我评论过,但也许你还没有读过。所以这是我的答案。

If you want to use Volley, you can refer to some following links:

如果您想使用Volley,可以参考以下链接:

  1. Working POST Multipart Request with Volley and without HttpEntity
  2. 使用Volley和没有HttpEntity工作POST多部分请求
  3. How to send a “multipart/form-data” POST in Android with Volley
  4. 如何使用Volley在Android中发送“multipart / form-data”POST
  5. Trouble Sending Multipart File with Boundary via Volley
  6. 无法通过Volley发送带有边界的多部分文件

Hope this helps

希望这可以帮助