【发布时间】:2016-07-05 10:44:32
【问题描述】:
阅读问题底部的编辑以了解可能的替代解决方案,直到找到解决方案。
这是一个使用 POSTMan 的带有两个参数的成功发布文件。我正在尝试对改造做同样的事情,但收到 BadRequest。
邮递员设置:
现在这是我在 Android 中执行此操作但失败的方式:
改造服务接口:
@Multipart
@POST("jobDocuments/upload")
Call<ResponseBody> upload(@Part("file") MultipartBody.Part file,@Part("folder") MultipartBody.Part folder,@Part("name") MultipartBody.Part name);
这是我的@Background 方法来运行生成上述服务的网络请求
CustDataClient service =
ServiceGenerator.createService(CustDataClient.class);
File file = new File(fileUri.getPath());
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part fileData =
MultipartBody.Part.createFormData("file", fileName, requestFile);
MultipartBody.Part folder =
MultipartBody.Part.createFormData("folder", "LeadDocuments");
MultipartBody.Part name =
MultipartBody.Part.createFormData("name", fileName);
// finally, execute the request
Call<ResponseBody> call = service.upload(fileData,folder,name);
try {
Response<ResponseBody> rr = call.execute();
ResponseBody empJobDocsResult = rr.body();//Bad Request here :(
Log.v("Upload", "success");
} catch (Exception ex) {
Log.e("Upload error:", ex.getMessage());
}
这是我的 Web Api 方法:
[Route("upload")]
[HttpPost]
public IHttpActionResult Upload()
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["file"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
var folder = HttpContext.Current.Request.Form["folder"];
var fileName = HttpContext.Current.Request.Form["name"];
fileName = string.IsNullOrEmpty(fileName) ? httpPostedFile.FileName : fileName;
// Get the complete file path
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Files/" + folder), fileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
return Ok(new OkMessage { Message = "File uploaded successfully", Path = "/Files/" + folder + "/" + fileName });
}
}
return BadRequest("File not uploaded");
}
请帮助我在哪里出错以及如何实现这一点,是否有任何简单的替代方案来改造?
[编辑] 此代码运行成功,感谢koush/ion:
Ion.with(getContext())
.load("POST", "http://www.dgheating.com/api/jobDocuments/upload")
.setMultipartParameter("folder", "LeadDocuments")
.setMultipartParameter("name", fileName)
.setMultipartFile("file", new File(imagePath))
.asJsonObject()
.setCallback(...);
【问题讨论】:
-
我在 Android 上遇到了同样的问题,确切地说是 4.1.1;现在使用带有 Ion 的示例解决了问题,现在我可以轻松地上传文件(在我的情况下为图像)而不会出现问题。您应该将 Ion 编辑作为回复发布(我猜)。
-
不,这不是问题的解决方案,而是替代方案(避免问题)。
-
这太糟糕了。你有没有找到解决这个问题的方法?
-
nvm,我刚看到你的编辑,Ion 会的。
标签: android file-upload retrofit android-networking retrofit2