怎么用Volley库上传图片?

时间:2014-11-24 19:32:40

标签: android json android-volley

我有一个图片,我想使用Volley库将此图像上传到我的网络服务,问题是我正在寻找一个如何做但仍未找到的。

我找到了这个,但对我不起作用:http://develop-for-android.blogspot.com.br/2014/01/using-volley-in-your-application.html

我该怎么做?

我正在尝试这个。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        fotoPerfil = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }     
}

UploadoImageToServer upload = new UploadoImageToServer();   
ApplicationController app = new UsuarioDAO().insert(usuario, upload.upload(fotoPerfil, em[0]), new UsuarioAdapter(){
    @Override
    public void usuarioIsAdded(Boolean result){
        Log.i("Adicionou: ", result + "");
        progress.dismiss();
    }                   
});
CustomVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(app);

public class UploadoImageToServer {
    public String upload(String image,String nomeImagem){
        Bitmap bitmap = BitmapFactory.decodeFile(image);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); 
        byte [] byte_arr = stream.toByteArray();
        String image_str = Base64.encodeBytes(byte_arr);
        return image_str;               
    }
}

/** add an user and upload your foto(image) */
public ApplicationController insert(Usuario u, String uploadFile, final UsuarioAdapter listener) {
    boolean insert = false; 

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("nome", u.getNome());
    params.put("email", u.getEmail());
    params.put("senha", u.getSenha());      
    params.put("tipo", "usuarios");
    params.put("acao", "add");
    params.put("device_tipo", "android");
    params.put("device", AndroidReturnId.getAndroidId());
    params.put("uploadedfile", uploadFile);
    Log.i("URL: ", urlPost.toString());

    ApplicationController apc = new ApplicationController(Method.POST, urlPost.toString(), params,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject obj) {
                try {
                    if(obj.getString("cod").equals("999")){                                                                             
                        listener.usuarioIsAdded(true);
                    }else{
                        listener.usuarioIsAdded(false);                                                     
                    }
                } catch (JSONException e) {                                                                     
                    e.printStackTrace();
                }
            }
        }, 
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Log.e("ERROR METHOD:", "insert in UsuarioDAO: " + arg0.getLocalizedMessage());
            }                                                                         
        });

    return apc;
}

2 个答案:

答案 0 :(得分:2)

我对凌空不是很熟悉,但试试下面的代码

// JSON请求

public MySampleImageUpload() { 
    JSONRequestResponse mResponse = new  
    JSONRequestResponse(mContext);

    Bundle parms = new Bundle();
    parms.putString("key_meail", "rojesh@demo.com");
    parms.setFile("key_url", image_path);

    mResponse.getResponse("sample_upload_data_url", REQUEST_CODE, this,
        parms);
}

//在SetFile&amp; getResponse代码

package com.fartogram.utils;

import java.io.File;

import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.examples.toolbox.MultipartRequest;
import com.android.volley.examples.toolbox.MyVolley;
import com.android.volley.toolbox.JsonObjectRequest;

public class JSONRequestResponse {

    public JSONRequestResponse(Context cntx) {
        mContext = cntx;
    }

    private final Context mContext;
    private int reqCode;
    private IParseListener listner;

    private boolean isFile = false;
    private String file_path = "", key = "";

    public void getResponse(String url, final int requestCode,
            IParseListener mParseListener) {
        getResponse(url, requestCode, mParseListener, null);
    }

    public void getResponse(String url, final int requestCode,
            IParseListener mParseListener, Bundle params) {
        this.listner = mParseListener;
        this.reqCode = requestCode;

        Response.Listener<JSONObject> sListener = new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if (listner != null) {
                    listner.SuccessResponse(response, reqCode);
                }
            }
        };

        Response.ErrorListener eListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (listner != null) {
                    listner.ErrorResponse(error, reqCode);
                }
            }
        };

        if (!isFile) {
            JsonObjectRequest jsObjRequest = new JsonObjectRequest(
                Request.Method.GET, url, null, sListener, 

eListener);
            MyVolley.getRequestQueue().add(jsObjRequest);
        } else {
                if (file_path != null) {
                    File mFile = new File(file_path);
                    MultipartRequest multipartRequest = 
    new MultipartRequest(url,eListener, sListener, key, mFile, params);
                MyVolley.getRequestQueue().add(multipartRequest);
            } 
        }
    }

    public boolean isFile() {
        return isFile;
    }


    public void setFile(String param, String path) {
        if (path != null && param != null) {
            key = param;
            file_path = path;
            this.isFile = true;
        }
    }

}

如果它适用于你,请将其标记为正确:)

答案 1 :(得分:2)

如果您想将图像上传为文件,则必须扩展请求并使用MultipartEntityBuilder。

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

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

    public ImageUploadWithVolley(String url, ErrorListener errorListener, Listener<T> listener, File imageFile)   {
        super(Method.POST, url, errorListener); 
        mListener = listener;
        yourImageFile = imageFile;        
        addImageEntity();
    }

    @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;
    }

    private void addImageEntity() {
        mBuilder.addBinaryBody("give your image name", yourImageFile, ContentType.create("image/jpeg"), yourImageFile.getName());
        mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
    }

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

    @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);
    }
}