java上传文件并保存到服务器----大文件上传

这段代码展示了三种文件保存方法:不依赖Spring的基本文件保存,使用Spring的MultipartFile保存,以及大文件上传。每种方法都涉及文件路径检查、创建父目录(如果不存在)以及写入文件内容。此外,还提供了从MultipartFile获取字节数组和InputStream的方法。

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

一般的文件上传(不依赖spring)

 /**
     * 保存文件
     *
     * @param path      文件绝对路径
     * @param fileBytes 文件字节数据
     * @throws ApiServiceException
     */
    public void save(String path,  byte [] fileBytes) throws ApiServiceException {
  
        //保存文件到对应位置
        File dir = new File(path);
        if (!dir.getParentFile()
                .exists()) {
            boolean mkdir = dir.getParentFile()
                               .mkdirs();
            if (!mkdir) {
                // 文件父路径创建失败,父路径['{0}']
                throw IctsServiceError.FILE_SAVE_ERROR.toException(
                        i18n(i18nPreFix + "file.parent.path.create.failure",
                                dir.getParentFile().getAbsolutePath()));
            }
        }
        try {
            FileUtils.writeByteArrayToFile(dir, fileBytes);
        } catch (IOException e) {
        //抛出异常  
        }
    }

依赖spring

/**
     * 保存文件
     *
     * @param path 文件绝对路径
     * @param file 文件数据
     * @throws ApiServiceException
     */
    private void save(String path, MultipartFile file) throws ApiServiceException {
        //保存文件到对应位置
        File dir = new File(path);
        if (!dir.getParentFile().exists()) {
            dir.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dir);
        } catch (IOException e) {
            //抛出异常
        }
    }

大文件上传(不依赖spring)

/**
     * 保存文件
     *
     * @param path      文件绝对路径
     * @param inputStream 文件流
     * @throws ApiServiceException
     */
    public void save(String path, InputStream inputStream) throws ApiServiceException {
        //保存文件到对应位置
        File dir = new File(path);
        boolean fileExists = dir.getParentFile() .exists();
        if (!fileExists) {
            boolean mkdir = dir.getParentFile().mkdirs();
            if (!mkdir) {
                // 文件路径创建失败,
            }
        }
        try (FileOutputStream fos = new FileOutputStream(dir)) {
            byte[] b = new byte[1024];
            while ((inputStream.read(b)) != -1) {
                fos.write(b);
            }
        } catch (IOException e) {
            //文件流转读取失败
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                  流关闭失败
                }
            }
        }
    }

从spring 的MultipartFile获取字节数组或者inputstream流

MultipartFile file
file.getBytes();
file.getInputStream()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值