使用改造2将图片上传到服务器 [英] Upload picture to server using retrofit 2

查看:121
本文介绍了使用改造2将图片上传到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先让我们看一下代码:

First of all lets look to the code:

public interface ApiInterface {
    @Multipart
    @POST("my/files/photo/")
    Call<FileUploadResponse> uploadPhoto(@Header("authorization") String auth,
                                     @Part MultipartBody.Part file,
                                     @Part("file-type") RequestBody fileType);
}

我这样称呼这个接口:

RequestBody body = RequestBody.create(MediaType
            .parse(getContentResolver().getType(fileUri)), file);
MultipartBody.Part avatarBody = MultipartBody.Part
            .createFormData(data, file.getName(), body);
RequestBody fileType = RequestBody.create(
            MediaType.parse("text/plain"), "profile");
client.uploadPhoto(getToken(), avatarBody, fileType);

我从服务器收到响应,提示未提供文件类型".如果我像这样更改uploadPhoto函数上的文件和文件类型的位置:

From server i'm getting response that "File type not provided". If i change places of file and filetype on uploadPhoto function like this:

@Multipart
@POST("my/files/photo/")
Call<FileUploadResponse> uploadPhoto(@Header("authorization") String auth,
                                 @Part("file-type") RequestBody fileType
                                 @Part MultipartBody.Part file);

我收到响应文件未提供". 我已经用自己写在JS上的代码检查了服务器:

I'm getting response "File not provided". I've checked server with my own code written on JS:

<!DOCTYPE html>
<script language="JavaScript" type="text/javascript" src="C://Users/User/Downloads/jquery-3.2.1.min.js"></script>

<form action="">
  <input type="text" name="authorize" id="authorize">
  <br>
  <input type="file" name="photo" accept="image/*" id="filechooser" onchange="onFileChange(this)" >
  <br>
  <input value="profile" type="text" name="file-type" id="type">
  <br>
  <input type="button" onclick="uploadFile()">
</form>


<script>
var blobFile;
function onFileChange(ss) {
	blobFile = ss.files[0];
	alert(blobFile);
}
function uploadFile() {

	var storedJWT = $('#authorize').val();
	var fileType = $('#type').val();
    var formData = new FormData();
    formData.append("file-type", fileType);
	formData.append("photo", blobFile);
	console.log(storedJWT);
    $.ajax({
       url: "url",
       type: "POST",
       data: formData,
	   headers: {
        authorization: storedJWT
	   },
       processData: false,
       contentType: false,
       success: function(response) {
		   console.log(response);
       },
       error: function(jqXHR, textStatus, errorMessage) {
           console.log(errorMessage);
       }
    });
}</script>

一切正常. JS上的脚本生成请求,如下所示:

everything working fine. Script on JS generating request like this:

Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
authorization:JWT token
Connection:keep-alive
Content-Length:67601
Content-Type:multipart/form-data; boundary=----
WebKitFormBoundary3MtpMA70hG41luF1
Host:localhost
------WebKitFormBoundary3MtpMA70hG41luF1
Content-Disposition: form-data; name="file-type"

profile
------WebKitFormBoundary3MtpMA70hG41luF1
Content-Disposition: form-data; name="photo"; filename="1231231313.jpg"
Content-Type: image/jpeg


------WebKitFormBoundary3MtpMA70hG41luF1--

,改装请求为:

Content-Type: multipart/form-data; boundary=238182ad-d99c-4d44-9ba6-7d178a14b2e9
Content-Length: 59776
authorization: JWT token
--238182ad-d99c-4d44-9ba6-7d178a14b2e9
Content-Disposition: form-data; name="photo"; filename="1502703422332.jpg"
Content-Type: image/jpeg
Content-Length: 59369
//bytes
--238182ad-d99c-4d44-9ba6-7d178a14b2e9
Content-Disposition: form-data; name="file-type"
Content-Transfer-Encoding: binary
Content-Type: text/plain; charset=utf-8
Content-Length: 7
profile
--238182ad-d99c-4d44-9ba6-7d178a14b2e9--

我不知道哪里可能出错...

I can't understand where can be error...

推荐答案

经过多次搜索,我发现服务器无法处理

After many search I found that server not handling headers like

Content-Transfer-Encoding: binary
Content-Type: text/plain; charset=utf-8

,我必须从我的请求中删除这些标头.解决方案是在我的API接口中创建上传函数,如下所示:

and i have to remove these headers from my request. And the solution is creating upload function in my API Interface like this:

@POST("my/files/photo/")
    Call<FileUploadResponse> uploadPhoto(@Header("Content-Type") String contentType,
                                          @Header("Authorization") String auth,
                                          @Body MultipartBody body);

并按以下方式调用此函数:

and call this function like:

ApiClient.ApiInterface client = ApiClient.getClient();
File file = new File(getPathFromUri(fileUri));
RequestBody fileBody = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
MultipartBody body = new MultipartBody.Builder().addFormDataPart("file-type", "profile")
                .addFormDataPart("photo", "image.png", fileBody)
                .build();
client.uploadPhoto("multipart/form-data; boundary=" + body.boundary(),
                    PrefManager.getInstance().getToken(), body);

结果,我在下面收到请求:

As result I get request below:

Content-Type: multipart/form-data; boundary=27ec8d66-d29d-48aa-a2fe-08c6664b10c7
Content-Length: 56412
Authorization: JWT token
--27ec8d66-d29d-48aa-a2fe-08c6664b10c7
Content-Disposition: form-data; name="file-type"
Content-Length: 7
profile
--27ec8d66-d29d-48aa-a2fe-08c6664b10c7
Content-Disposition: form-data; name="photo"; filename="image.png"
Content-Type: image/jpeg
Content-Length: 56089
/* bytes */
--27ec8d66-d29d-48aa-a2fe-08c6664b10c7--

它工作正常.

这篇关于使用改造2将图片上传到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆