簡體   English   中英

在Android Volley的http發布服務中以用戶名作為發布參數並以圖片作為正文上傳圖像

[英]Image upload with username as post parameter and Image as body in http post service in android volley

我正在嘗試使用android中的volley將post參數作為用戶名和圖像作為多格式數據發送。 我正在創建主體以及發送參數,但是后期服務主體似乎以某種方式覆蓋了服務器提供的參數。 我正在使用自定義的請求類,其中編寫的代碼如下:

public abstract class CustomJsonRequest<T> extends Request<T> {
 ................

  @Override
protected Map<String, String> getParams() throws AuthFailureError {
   // return super.getParams();
    HashMap<String, String> map = new HashMap<>();
    map.put("userName", requestParameters.get("userName"));

    return map;
}

public byte[] getBody() throws AuthFailureError {
    return createPostBody(requestParameters).getBytes();
}


private String createPostBody(Map<String, String> params) {
    StringBuilder sbPost = new StringBuilder();
    if (params != null) {

        // for (String key : params.keySet()) {
        if (params.get("image") != null) {
            sbPost.append("\r\n" + "--" + BOUNDARY + "\r\n");
            sbPost.append("Content-Disposition: form-data; name=\"" + "image" + "\"" + "\r\n\r\n");
            sbPost.append(params.get("image"));
        }
        //}
    }
    return sbPost.toString();
}

 }

在調試時,我可以看到沒有調用getParameters。 我的目標是在Android中使用凌空發送帶有圖像作為其發布正文的發布參數。 在Ios中,它使用alamofire,並通過以下代碼成功上傳。

  func uploadImage(userImage: UIImage, completion: (result: RestResultType) -> Void) {
    let parameters = ["userName": localData.getAccessToken()]
    let url = domain + RestExt.imageUpload.rawValue

    Alamofire.upload(.POST, url, multipartFormData: {
        multipartFormData in

        let imageData = UIImageJPEGRepresentation(userImage, 0.5)
        if(imageData == nil) {
            completion(result: .Error(e: method(code: "ImageConversionError",message: "")))
            return
        }

        multipartFormData.appendBodyPart(data: imageData!, name: "image", fileName: "image.png", mimeType: "image/png")
        for (key, value) in parameters {
            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
        }

        }, encodingCompletion: {
            encodingResult in

            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON {
                    response in
                    switch response.result {
                    case .Success(let JSONResponse) :
                        let response = JSONResponse as! NSDictionary
                        let error = response.objectForKey("error") as? NSDictionary
                        if(error != nil) {
                            completion(result: .Error(e: method(JSONDictionary: error!)))
                        }
                        else {
                            completion(result: .Success(r: response))
                        }

                    case .Failure(let err):
                       }
                }
            case .Failure(let encodingError):
                print(encodingError)
            }
    })
} 

我曾經發送圖像轉換為字符串。 這對我有用...

public static void uploadImage(final String userName, final Bitmap bitmap, final Bitmap thumbBitmap, final Activity activity) {
    //Showing the progress dialog

    String UPLOAD_URL = "your/url/address";
    RequestQueue queue = Volley.newRequestQueue(activity);
    final String image = getStringImage(bitmap);

    final ProgressDialog loading = ProgressDialog.show(activity, "Uploading...", "Please wait...", false, false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();
                }
            }) {

        protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String image = getStringImage(bitmap);
            //Getting Image Name

            String name = "user_name";

            //Creating parameters
            Map<String, String> params = new Hashtable<String, String>();

            //Adding parameters
            params.put("image", image);
            params.put("userName", name);

            //returning parameters
            return params;
        }
    };

    //Adding request to the queue
    queue.add(stringRequest);
}

   public static String getStringImage(Bitmap bmp) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

    return encodedImage;
}

暫無
暫無

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

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