Android 一个参数多个文件上传

来源:互联网 发布:协同过滤算法详解 编辑:程序博客网 时间:2024/05/15 02:50

以上是我的上传接口需求   刚开始我就用了Xutils框架传声音和多个图

params.addBodyParameter("voice", new File(audioPath1));

容我BB下

这里点进去可以看到它是Map集合添加参数的 多个图片的 Map的key是唯一的  上传的话只有最后一个在Map容器里  所以这个方案不成立

然后尝试每个图片独立上传,结果服务器那边还是看到只有一个图片资源 这个不知道什么原因  后台的是个一直逼逼说就这样, 没办法 后台是大爷  我换方式

再后来尝试 用原生方法上传

HttpURLConnection 

conn.setRequestMethod("POST");conn.setRequestProperty("connection", "keep-alive");conn.setRequestProperty("Charset", "UTF-8");conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);// 拼接文本类型的参数StringBuilder textSb = new StringBuilder();if (textParams != null) {    for (Map.Entry<String, String> entry : textParams.entrySet()) {        textSb.append(PREFIX).append(BOUNDARY).append(LINE_END);        textSb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END);        textSb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END);        textSb.append("Content-Transfer-Encoding: 8bit" + LINE_END);        textSb.append(LINE_END);
代码写出来是对的 能跟服务器对接  但是差后台数据库竟然没有抓取到声音、图片数据 ----白做  原因是上面的方式有好多字段需要拼接的  也不知道拼什么 放弃了


再接着还用了OKHttp框架 这个框架查资料的时候 我看到了希望  集成到项目完成时很激动  结果运行一下  报个什么过时错误 还有个找不到什么类   失望


--------------------------------------------------逼逼完了----------------------------------------------------


重点:项目用了 libs/volly-1.0.11.jar

创建一个类 

package com.kinth.troubleshootingforccb.workbentch;/** * 作者:Administrator on 2016/7/4 0004 15:50<br> * 邮箱:linsiqick@foxmail.com<br> * 备注:<br> * <br> */import android.util.Log;import com.android.volley.AuthFailureError;import com.android.volley.NetworkResponse;import com.android.volley.Request;import com.android.volley.Response;import com.android.volley.VolleyLog;import com.android.volley.toolbox.HttpHeaderParser;import org.apache.http.entity.mime.MultipartEntity;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.entity.mime.content.StringBody;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;public class MultipartRequest extends Request<String> {    private MultipartEntity entity = new MultipartEntity();    private final Response.Listener<String> mListener;    private List<File> mFileParts;    private String mFilePartName;    private Map<String, String> mParams;    /**     * 单个文件     *     * @param url     * @param errorListener     * @param listener     * @param filePartName     * @param file     * @param params     */    public MultipartRequest(String url, Response.ErrorListener errorListener,                            Response.Listener<String> listener, String filePartName, File file,                            Map<String, String> params) {        super(Method.POST, url, errorListener);        mFileParts = new ArrayList<File>();        if (file != null) {            mFileParts.add(file);        }        mFilePartName = filePartName;        mListener = listener;        mParams = params;        buildMultipartEntity();    }    /**     * 多个文件,对应一个key     *     * @param url     * @param errorListener     * @param listener     * @param filePartName     * @param files     * @param params     */    public MultipartRequest(String url, Response.ErrorListener errorListener,                            Response.Listener<String> listener, String filePartName,                            List<File> files, Map<String, String> params) {        super(Method.POST, url, errorListener);        mFilePartName = filePartName;        mListener = listener;        mFileParts = files;        mParams = params;        buildMultipartEntity();    }    private static String soundName;    private static File soundFile;    public static void addSoundFile(String name, File file) {        soundName = name;        soundFile = file; //自己加的方法 添加声音文件    }    private void buildMultipartEntity() {        if (soundName != null && soundFile != null) {            entity.addPart(soundName, new FileBody(soundFile));        }        if (mFileParts != null && mFileParts.size() > 0) {            for (File file : mFileParts) {                entity.addPart(mFilePartName, new FileBody(file));            }            long l = entity.getContentLength();            Log.d("MultipartRequest", "l:" + l);        }        try {            if (mParams != null && mParams.size() > 0) {                for (Map.Entry<String, String> entry : mParams.entrySet()) {                    entity.addPart(                            entry.getKey(),                            new StringBody(entry.getValue(), Charset                                    .forName("UTF-8")));                }            }        } 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) {        if (VolleyLog.DEBUG) {            if (response.headers != null) {                for (Map.Entry<String, String> entry : response.headers                        .entrySet()) {                    VolleyLog.d(entry.getKey() + "=" + entry.getValue());                }            }        }        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));    }    /*     * (non-Javadoc)     *     * @see com.android.volley.Request#getHeaders()     */    @Override    public Map<String, String> getHeaders() throws AuthFailureError {        VolleyLog.d("getHeaders");        Map<String, String> headers = super.getHeaders();        if (headers == null || headers.equals(Collections.emptyMap())) {            headers = new HashMap<String, String>();        }        return headers;    }    @Override    protected void deliverResponse(String response) {        mListener.onResponse(response);    }}

使用方法 


/** * 上传 * @param url 地址 * @param audioPath 声音文件地址 * @param troubleId id */private void upload(String url, String audioPath, String troubleId) {    final RequestQueue requestQueue = Volley.newRequestQueue(mContext);    Map<String, String> map = HttpRequstPost.newMap();    map.put("troubleId", troubleId);    List<File> list = new ArrayList<>();    for (String img : listPath) { //图片集合        list.add(new File(img));    }    MultipartRequest.addSoundFile("voice", new File(audioPath));    MultipartRequest multipartRequest = new MultipartRequest(url, new Response.ErrorListener() {        @Override        public void onErrorResponse(VolleyError volleyError) {            Toast.makeText(getContext(), volleyError.getMessage(), Toast.LENGTH_SHORT).show();        }    }, new Response.Listener<String>() {        @Override        public void onResponse(String s) {            Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();        }    }, "picture", list, map);    requestQueue.add(multipartRequest);}

--------------------------------------来自抄袭,忘了复制原文路径...--------------------------------------------


0 0