我正在製作一個應用程序,我必須使用Volley
上傳圖片。我試圖谷歌,但沒有發現類似的東西。如何使用Volley
發佈圖像時多部分上傳圖像並添加參數,如user_id
?Android凌空上傳圖片
使用Retrofit
不適用於我的情況。
我正在製作一個應用程序,我必須使用Volley
上傳圖片。我試圖谷歌,但沒有發現類似的東西。如何使用Volley
發佈圖像時多部分上傳圖像並添加參數,如user_id
?Android凌空上傳圖片
使用Retrofit
不適用於我的情況。
首先創建一個文件MultipartRequest
如下:
public class MultipartRequest extends Request<String> {
private MultipartEntityBuilder entity = MultipartEntityBuilder.create();
private final Response.Listener<String> mListener;
private final File file;
private final HashMap<String, String> params;
public MultipartRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener, File file, HashMap<String, String> params)
{
super(Method.POST, url, errorListener);
mListener = listener;
this.file = file;
this.params = params;
buildMultipartEntity();
buildMultipartEntity2();
}
private void buildMultipartEntity()
{
entity.addBinaryBody(KEY_IMAGE, file, ContentType.create("image/jpeg"), file.getName());
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
try
{
for (String key : params.keySet()) {
entity.addPart(key, new StringBody(params.get(key)));
}
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
@Override
public String getBodyContentType()
{
return entity.build().getContentType().getValue();
}
@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;
}
@Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.build().writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
/**
* copied from Android StringRequest class
*/
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
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));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}}
在你的活動只是讓multipart請求信息如下:
public void uploadImage()
{
try {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
HashMap params = new HashMap<String, String>();
params.put(KEY_NAME, name);
MultipartRequest sr = new MultipartRequest(UPLOAD_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if ((pDialog != null) && pDialog.isShowing()) {
pDialog.dismiss();
}
Log.d("file", f + "");
Log.d("", ".......response====" + response.toString());
////////
try {
JSONObject object = new JSONObject(response);
String serverCode = object.getString("code");
if (serverCode.equalsIgnoreCase("0")) {
}
if (serverCode.equalsIgnoreCase("1")) {
try {
if ("1".equals(serverCode)) {
JSONObject object1 = object.getJSONObject("data");
}
}
使用改造2:
您需要使用OkHttp的RequestBody類,並將您的文件封裝到請求正文(表示您的用戶標識)。
1)創建界面
public interface FileUploadService {
@Multipart
@POST("/upload")
Call<String> upload(
@Part("myfile\"; filename=\"image.png\" ") RequestBody file,
@Part("userid") RequestBody userid);
}
2)在活動代碼:
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);
String userid = "your_userid";
RequestBody data =
RequestBody.create(MediaType.parse("multipart/form-data"), userid);
File file = new File("path/to/your/file");
RequestBody requestBody =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
Call<String> call = service.upload(requestBody, data);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.v("Upload", "success");
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("Upload", t.getMessage());
}
});
參考鏈接:https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server
是利用凌空:試試這個http://stackoverflow.com/a/29430765/5275436 –