I use this configuration and code to upload a file from my android app to a web api method. but it doesn't work. in my build.grad:
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
my api service:
public interface RetrofitService {
@Multipart
@POST("/api/scrap/PostImage")
Call<String> uploadImage(@PartMap() Map<String, RequestBody> mapFileAndName);
}
My upload method:
public class UploadFileRetrofit {
private String url="http://192.168.1.2:8870";
private String endPoint = "http://192.168.1.2:8870";
public void upload(String path,String fileName) {
path+=fileName;
final File file = new File(path);
Retrofit retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitService retrofitService=retrofit.create(RetrofitService.class);
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
HashMap<String,RequestBody> map=new HashMap<>();
map.put("file\"; filename=\""+fileName+"",requestBody);
Call<String> call = retrofitService.uploadImage(map);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Response<String> response, Retrofit retrofit) {
if(response!=null){
Log.i("upload","is success:" +response.message());
}else{
Log.i("upload","response is null");
}
}
@Override
public void onFailure(Throwable t) {
Log.i("upload","onFailure: "+t.getMessage());
}
});
}
and in my web api method on server:
[AcceptVerbs("GET","POST")]
public Task<HttpResponseMessage> PostImage(HttpPostedFileBase uploaded_file)
{
//System.IO.StreamWriter sw2 = new StreamWriter(HttpContext.Current.Server.MapPath("~/upload/tt.txt"));
//sw2.Write("start");
//sw2.Close();
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = System.Web.HttpContext.Current.Server.MapPath("~/upload");
var provider = new MultipartFormDataStreamProvider(root);
var task = request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(o =>
{
string file1 = provider.FileData.First().LocalFileName;
// this is the file name on the server where the file was saved
return new HttpResponseMessage()
{
Content = new StringContent("File uploaded.")
};
});
return task;
}
but I get response error code 500 which is Internal Server Error. What's wrong with this?