Retrofit 上传文件

本文介绍两种文件上传的方法:一种使用LiveData和MultipartBody.Part进行图片上传处理;另一种通过直接操作byte[]并设置MediaType来实现文件上传。同时展示了如何将文件转换为二进制数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件流的形式:

    @Multipart
    @POST("/upload")
    LiveData<ApiResponse<String>> voucherUpload(@Part MultipartBody.Part part);
public LiveData<ApiResponse<String>> getVoucherUpload(LiveData path) {
        LiveData voucherData = Transformations.switchMap(data, input -> {
            File file = new File(path);
            RequestBody fileRQ = RequestBody.create(MediaType.parse("image/*"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("picture", file.getName(), fileRQ);
            return getApiService().voucherUpload(part);
        });
        return voucherData;
    }

方式二:

public static Call<Bean> upload(UploadApi api,byte[] img) {
    Map<String, Object> params = new HashMap<>();
    RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), img);
    return api.upload(params,requestBody);
}
 
 
@Multipart
@POST("upload")
Call<Bean> upload(@QueryMap Map<String, Object> maps, @Part("img\"; filename=\"img.jpg\"")RequestBody img);
 
 
MediaType.parse("multipart/form-data")    对应    @Multipart
 
@Part("img\"; filename=\"img.jpg\"")RequestBody img    
  
img是上传的时候,参数名

文件转为二进制:

/***
     * @param spec 图片路径
     * @return url请求结果
     */
    public static byte[] BufferStreamForByte(String spec) {
        byte[] content = null;
        try {
            BufferedInputStream bis = null;
            ByteArrayOutputStream out = null;
            try {
                FileInputStream input = new FileInputStream(spec);
                bis = new BufferedInputStream(input, 1024);
                byte[] bytes = new byte[1024];
                int len;
                out = new ByteArrayOutputStream();
                while ((len = bis.read(bytes)) > 0) {
                    out.write(bytes, 0, len);
                }
                bis.close();
                content = out.toByteArray();
            } finally {
                if (bis != null)
                    bis.close();
                if (out != null)
                    out.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return content;
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值