Retrofit 上传文件

来源:互联网 发布:pl10空空导弹 知乎 编辑:程序博客网 时间:2024/06/05 16:55

Retrofit 上传文件

服务器接收代码

  @ResponseBody    @RequestMapping(value = "/file", method = RequestMethod.POST)    public String getfile(@RequestParam("file") MultipartFile file,                          @RequestParam("title") String title) throws IOException {        String str = file.getOriginalFilename();        System.out.println(file.getSize());        System.out.println(str);        System.out.println(title);        InputStream in = file.getInputStream();        byte[] bt = new byte[1024];        int len;        File sf = new File("d:\\image\\");        if (!sf.exists()) {            sf.mkdirs();        }        OutputStream outputStream = new FileOutputStream(sf.getPath() + "\\" + str);        while ((len = in.read(bt)) != -1) {            outputStream.write(bt, 0, len);        }        outputStream.close();        in.close();        return str;    }

Retrofit上传

    @Multipart    @POST("file")    Call<ResponseBody> file(@Part MultipartBody.Part part,                             @Part("title") String title);
 public static Call<ResponseBody> file(File file, String title){        return service.file(MultipartBody.Part                        .createFormData("file", file.getName(),                                RequestBody.create(MediaType.parse("image/jpg"), file)),title);    }
原创粉丝点击