uploadPhoto(@Header("A-6ren">
gpt4 book ai didi

java - 上传图片到android服务器

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:30 25 4
gpt4 key购买 nike

我必须使用retrofit2捕获图像并将其上传到服务器我的API

    @Multipart
@POST("photo/")
Call<NetWorkResponse<String>> uploadPhoto(@Header("Authorization") String token,
@Part("category") String category,
@Part MultipartBody.Part photo);

我上传照片的方法

public static void uploadPhoto(String nfToken, String category, File photoFile) {


RequestBody filePart = RequestBody.create(MediaType.parse("image/jpeg"), photoFile);

MultipartBody.Part file = MultipartBody.Part.createFormData("photo", photoFile.getName(), filePart);

Call<NetWorkResponse<String>> call = nfApi.uploadPhoto(nfToken, category, file);
call.enqueue(new Callback<NetWorkResponse<String>>() {
@Override
public void onResponse(Call<NFNetWorkResponse<String>> call, Response<NetWorkResponse<String>> response) {

if (response.isSuccessful()) {
NetWorkResponse<String> netWorkResponse = response.body();

} else {

}
}

@Override
public void onFailure(Call<NetWorkResponse<String>> call, Throwable t) {

}
});
}

我的照片文件 Uri:file:///storage/emulated/0/Pictures/Food/IMG_20170731_094856_2128319239.jpg

当我将文件上传到服务器时,我收到错误 Bad Request,代码 400。这可能表明我的参数错误,但我很确定这没有任何问题。我猜图片有问题,MediaType.parse(“image/jpeg”)有问题

相反,应该是:

 File f = new File(mCurrentPhotoPath);
Uri pictureUri = Uri.fromFile(f);
String contentType = getContentResolver().getType(pictureUri);
MediaType.parse(contentType)

但问题是 Uri 路径是 file://而不是 content://所以 contentType 为 null

知道我将照片上传到服务器时出了什么问题吗

最佳答案

代替照片文件网址file:///storage/emulated/0/Pictures/Food/IMG_20170731_094856_2128319239.jpg

传递这个/storage/emulated/0/Pictures/Food/IMG_20170731_094856_2128319239.jpg

关于java - 上传图片到android服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45409238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com