java实现文件上传,通过form表单上传和通过传json格式的body体

java实现文件上传,通过form表单上传和通过传json格式的body体

  • 1、两种上传方式介绍
    • 1.1、form表单上传
    • 1.2、通过body体中放json体上传
  • 2、代码实现
    • 2.1、form表单上传
    • 2.2、通过body体中放json体上传
  • 3、文件操作小工具
    • 3.1、File转MultipartFile

1、两种上传方式介绍

1.1、form表单上传

form表单上传,是用的最多的一种上传方式了, 上传方的请求头中的Content-Type是multipart/form-data。
接收方的Controller中的参数是MultipartFile。

1.2、通过body体中放json体上传

这种方式用的比较少
使用场景:
1、比如我们需要调用上传文件接口,接口中参数的类型是String,而不是MultipartFile。
2、调用第三方接口,接口原本定的是body体放json传数据,现在又要在该接口中新增个上传文件的参数,上传文件方和接收文件方又都不想改为form表单上传。
实际上这种方式,是把File文件进行base64编码成一个字符串上传,把文件当一个普通字符串上传,接收方把接收的字符串解码成byte[],然后再把byte[]转File就可以了。

2、代码实现

温馨提示: 下面代码都是在SprigBoot项目中使用的。可能用使用Spring中的一些包

2.1、form表单上传

这个方式最常用,就不贴代码了

2.2、通过body体中放json体上传

	public static void main(String[] args) throws Exception {
        File file = new File("D:\\a.txt");
        //Base64使用的是hutool包中的
        //编码
        String encode = Base64.encode(file);
        //解码
        byte[] decode = Base64.decode(encode);
        //byte数组转File
        byteArrayToFile(decode, "D:/a.txt");
    }


    /**
     * byte数组转File
     *
     * @param byteArray  字节数组
     * @param targetPath 目标路径
     */
    public static void byteArrayToFile(byte[] byteArray, String targetPath) {
        InputStream in = new ByteArrayInputStream(byteArray);
        File file = new File(targetPath);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

3、文件操作小工具

3.1、File转MultipartFile

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
    /**
     * file转MultipartFile
     *
     * @param file
     * @return
     */
    public MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem(file.getName(), MediaType.MULTIPART_FORM_DATA_VALUE, true, file.getName(), (int) file.length(), file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

你可能感兴趣的:(自创,java,json,前端)