簡體   English   中英

Android凌空上傳圖片

[英]Android volley upload image

我正在制作一個應用程序,必須使用Volley上傳圖像。 我試圖用Google搜尋,但沒有找到類似的東西。 使用Volley發布此圖像時,如何進行圖像的多部分上傳並添加諸如user_id參數?

在我的情況下,不建議使用Retrofit

首先創建文件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");

                            }
                        }

使用改造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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM