有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓中将文件上传到服务器?

如何使用volley library从移动设备向服务器发送文件(数据)

下面我列出了我的参数,请帮我解决这个问题

        Map<String, String> mHeaderPart= new HashMap<>();
            mHeaderPart.put("Content-type", "multipart/form-data;");
            mHeaderPart.put("Authorization", authorizationKey);


    //String part
            Map<String, String> mStringPart= new HashMap<>();
            mStringPart.put("candidate_id", SessionStores.getBullHornId(getActivity()));
            mStringPart.put("externalID", "portpolio");
            mStringPart.put("fileCount", "2");//number of files
            mStringPart.put("fileType", "SAMPLE");
            mStringPart.put("platform", "安卓");

//file param

     Map<String, File> mFilePartData= new HashMap<>();

在上面的文件参数中,我必须添加n个文件并将其发送到服务器。我如何从设备中获取文件,并使用param添加n个文件,并将其发送到服务器。如果有人可以,请给我建议

如果有人有使用截击发送多个文件的例子,请指导我。提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    Volly不提供在服务器上使用multi-part上传文件的直接方式

    要使用volly上传多个文件,请执行以下步骤:

    步骤1:创建一个名为MultipartRequest的新类。从volly扩展请求的java,如下所示:

    import com.android.volley.AuthFailureError;
    
    import com.android.volley.NetworkResponse;
    
    import com.android.volley.ParseError;
    
    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.HttpEntity;
    
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    
    import org.apache.http.entity.mime.content.FileBody;
    
    import java.io.ByteArrayOutputStream;
    
    import java.io.File;
    
    import java.io.IOException;
    
    import java.io.UnsupportedEncodingException;
    
    import java.util.HashMap;
    
    import java.util.Map;
    
    public class MultipartRequest extends Request<String> { private MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create(); HttpEntity entity;
    
        private HashMap<String, File> sendFile = new HashMap<>();
    
        /**
        * 
        * @param url               url
        * @param errorListener     volly error listenere
        * @param sendFile          HashMap with key as file name and value as file  object
        */
    
        public MultipartRequest(String url, Response.ErrorListener errorListener,   HashMap<String, File> sendFile) {
        super(Method.POST, url, errorListener);
    
        this.sendFile = sendFile;
        buildMultipartEntity();
        entity = entitybuilder.build();
        }
    
        private void buildMultipartEntity() {
    
        if (sendFile != null)
            for (Map.Entry<String, File> entry : sendFile.entrySet()) {
                entitybuilder.addPart(entry.getKey(), new    FileBody(entry.getValue()));
    
                // here you can set key as filename
                // value will be the file object to be upload
    
            }
        }
    
        @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 networkResponse) {
        try {
            String json = new String(
                    networkResponse.data,   HttpHeaderParser.parseCharset(networkResponse.headers));
            return Response.success(json, HttpHeaderParser.parseCacheHeaders(networkResponse));
    
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
        }
    
        @Override
        protected void deliverResponse(String s) {
    
        //Your response
    
        }
    }
    

    第二步:

    从你的活动中:

    public void executeMultipart(String url,HashMap<String, File> fileData) { 
        try { MultipartRequest mRequest = new MultipartRequest(url , new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) {
    
                }
            },fileData);
            mRequest.setRetryPolicy(new DefaultRetryPolicy(
                    (int) TimeUnit.SECONDS.toMillis(20),
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        } catch (Exception e) {
            e.printStackTrace();
        }
        }
    

    第3步:在应用程序构建中。gradle文件添加:

    compile('org.apache.httpcomponents:httpmime:4.3.6') { exclude module: 'httpclient' }
    

    注:来自API 22组织。阿帕奇。http。HttpEntity已被弃用,因此最好使用URLConnection或改型库,两者都有各自的优点和缺点