如何在Android中使用Retrofit上传文件?

时间:2016-06-19 12:34:14

标签: android web-services file-upload retrofit retrofit2

我使用此配置和代码将文件从我的Android应用程序上传到web api方法。但它不起作用。 在我的build.grad:

    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

我的api服务:

public interface RetrofitService {
@Multipart
@POST("/api/scrap/PostImage")
Call<String> uploadImage(@PartMap() Map<String, RequestBody> mapFileAndName);

}

我的上传方式:

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());
        }
    });
}

和我在服务器上的web api方法:

        [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; 
    }

但是我收到响应错误代码500,即内部服务器错误。这有什么问题?

0 个答案:

没有答案