gpt4 book ai didi

java - android中如何将文件上传到服务器?

转载 作者:太空宇宙 更新时间:2023-11-04 12:12:11 25 4
gpt4 key购买 nike

如何使用 volley 库将文件(数据)从移动设备发送到服务器。

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

        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", "android");

//file param

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

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

如果有人有使用 volley 发送带有参数的多个文件的示例,请指导我。提前致谢。

最佳答案

Volly 不提供使用分段方式在服务器上上传文件的直接方法。

要使用 volly 上传多个文件,请按照以下步骤操作:

第 1 步:创建一个名为 MultipartRequest.java 的新类,该类扩展了 volly 中的 Request,如下所示:

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

}
}

第 2 步:

根据您的 Activity :

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 步:在您的应用 build.gradle 文件中添加:

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

注意:从 API 22 开始,org.apache.http.HttpEntity 已被弃用,因此最好使用 URLConnection 或使用改造库,两者都有自己的优点和缺点

关于java - android中如何将文件上传到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com