我正在尝试使用改造上传文件,将其发送到服务器端并将该文件保存在我的上传文件夹中。
这是我的改造API实例:
@Multipart
@POST("file/uploaddocument")
Call<ResponseBody> uploadFile(@Part MultipartBody.Part file );
UploadFile:
private void uploadFile(Uri fileUri) {
// create upload service client
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
MyApiEndpointInterface apiService =
retrofit.create(MyApiEndpointInterface.class);
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = Utils.getFileForUri(fileUri);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", file.getName(), requestFile);
// finally, execute the request
Call<ResponseBody> call = apiService.uploadFile(body);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
UploadProgressDialog.dismiss();
Log.v("Upload", "success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
UploadProgressDialog.dismiss();
Log.e("Upload error:", t.getMessage());
}
});
}
我在点击按钮时调用此方法:
uploadFile(myfileuri);
这是我的Web API调用(这是否正确?如果不是如何从客户端接受图像?)
<HttpPost>
<Route("api/File/UploadDocument", Name:="UploadDocument")>
Public Function Upload() As HttpResponseMessage
Try
Dim UploadedPath As String = HttpContext.Current.Server.MapPath("~/UploadedFiles")
Dim httpRequest = HttpContext.Current.Request
If httpRequest.Files.Count > 0 Then
For Each file As String In httpRequest.Files
Dim postedFile = httpRequest.Files(file)
postedFile.SaveAs(UploadedPath + "/")
Next
Else
End If
Dim message = Request.CreateResponse(HttpStatusCode.OK, "True")
Return message
Catch ex As Exception
Return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)
End Try
End Function
答案 0 :(得分:0)
我就是这样做的......在这里张贴以便其他人可能会发现它很有用
<HttpPost, Route("api/UploadFile")>
Public Function Post() As HttpResponseMessage
Try
Dim httpRequest = HttpContext.Current.Request
If httpRequest.Files.Count < 1 Then
Return Request.CreateResponse(HttpStatusCode.BadRequest)
End If
For Each file As String In httpRequest.Files
Dim postedFile = httpRequest.Files(file)
Dim filePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + postedFile.FileName)
' NOTE: To store in memory use postedFile.InputStream
postedFile.SaveAs(filePath)
Next
Return Request.CreateResponse(HttpStatusCode.NoContent)
Catch ex As Exception
Return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)
End Try
End Function