Java通过文件流和文件地址下载文件

在这里插入图片描述

通过文件流下载文件

如何使用 MultipartFile 进行文件上传、下载到本地,并返回保存路径呢:

import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileUtils {

    private static final String UPLOAD_DIR = "/path/to/upload/directory/"; // 修改为您的上传目录

    public static String saveFileAndGetPath(MultipartFile file) throws IOException {
        String originalFileName = file.getOriginalFilename();
        String fileName = generateFileName(originalFileName);
        String filePath = UPLOAD_DIR + fileName;

        try (InputStream inputStream = file.getInputStream();
             BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath))) {

            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

        return filePath;
    }

    private static String generateFileName(String originalFileName) {
        String timestamp = Long.toString(System.currentTimeMillis() / 1000); // 时间戳精确到秒
        int dotIndex = originalFileName.lastIndexOf(".");
        String extension = (dotIndex != -1) ? originalFileName.substring(dotIndex) : "";
        String fileNameWithoutExtension = (dotIndex != -1) ? originalFileName.substring(0, dotIndex) : originalFileName;

        return fileNameWithoutExtension + "_" + timestamp + extension;
    }
}

用于在 Spring Boot 应用中获取文件流,然后处理上传的文件,将文件保存到指定目录并返回保存的文件路径。下面对代码的各个部分进行简要介绍:

  1. 上传目录设置:在这个示例中,UPLOAD_DIR 常量用于定义上传文件的目录路径。您需要将其修改为您实际希望保存上传文件的路径。

  2. 保存文件并获取路径saveFileAndGetPath 方法接收一个 MultipartFile 对象,表示上传的文件。在该方法中,将上传的文件保存到指定的目录中,并返回保存后的文件路径。

  3. 生成文件名generateFileName 方法用于生成带时间戳的新文件名,以避免文件名冲突。它使用当前时间的时间戳(精确到秒)作为文件名的一部分,并保留原始文件名的扩展名。

  4. 上传逻辑:在 saveFileAndGetPath 方法中,使用 MultipartFile 对象的输入流来读取上传文件的内容,并通过输出流将内容写入指定的文件路径。

通过文件地址下载文件

package com.ruoyi.im.utils;

import com.ruoyi.common.config.RuoYiConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class FileUtils {

    /**
     * 默认路径
     */
    private static String defaultBaseDir = RuoYiConfig.getProfile();

    /**
     * 下载并保存文件
     *
     * @param url              url
     * @param originalFileName 原始文件名字
     * @return {@code String}
     */
    public static String downloadAndSaveFile(String url, String originalFileName) {
        try {
            URL fileUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
            connection.setRequestMethod("GET");

            String fileName = generateFileNameWithTimestamp(originalFileName);
            String savePath = generateSavePath(fileName);

            try (InputStream inputStream = connection.getInputStream();
                 BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(savePath))) {

                byte[] buffer = new byte[4096];
                int bytesRead;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                return convertToReturnPath(savePath);
            }

        } catch (IOException e) {
            e.printStackTrace();
            log.error("Error: " + e.getMessage());
            return null;
        }
    }

    /**
     * 生成文件名字和时间戳
     *
     * @param originalFileName 原始文件名字
     * @return {@code String}
     */
    private static String generateFileNameWithTimestamp(String originalFileName) {
        String timestamp = getCurrentTimestamp();
        int dotIndex = originalFileName.lastIndexOf(".");
        String extension = "";
        if (dotIndex != -1) {
            extension = originalFileName.substring(dotIndex);
            originalFileName = originalFileName.substring(0, dotIndex);
        }
        return originalFileName + "_" + timestamp + extension;
    }

    /**
     * 生成保存路径
     *
     * @param fileName 文件名称
     * @return {@code String}
     */
    private static String generateSavePath(String fileName) {
        Date currentDate = new Date();
        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
        SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
        SimpleDateFormat dayFormat = new SimpleDateFormat("dd");

        String year = yearFormat.format(currentDate);
        String month = monthFormat.format(currentDate);
        String day = dayFormat.format(currentDate);

        String filePath = defaultBaseDir + "/upload/" + year + "/" + month + "/" + day + "/";
        return filePath + fileName;
    }

    /**
     * 转换返回路径
     *
     * @param filePath 文件路径
     * @return {@code String}
     */
    private static String convertToReturnPath(String filePath) {
        String relativePath = filePath.replace(defaultBaseDir, "/profile");
        return relativePath.replace("\\", "/");
    }

    /**
     * 获得当前时间戳
     *
     * @return {@code String}
     */
    public static String getCurrentTimestamp() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date currentDate = new Date();
        return dateFormat.format(currentDate);
    }
}

用于根据文件URL地址处理文件的下载、保存和路径转换操作。下面对代码的各个部分进行简要介绍:

  1. 导入和日志记录:导入了所需的类和包,使用了 @Slf4j 注解来自动生成日志记录代码。

  2. 默认路径和方法

    • defaultBaseDir:默认的文件保存路径,通过 RuoYiConfig.getProfile() 方法获取,您需要将其设置为实际的文件保存目录。
    • downloadAndSaveFile(String url, String originalFileName):下载文件并保存到本地,接收文件的 URL 和原始文件名作为参数。
    • generateFileNameWithTimestamp(String originalFileName):根据原始文件名生成带时间戳的新文件名。
    • generateSavePath(String fileName):根据文件名生成保存的文件路径,包括年、月、日的子目录。
    • convertToReturnPath(String filePath):将文件路径转换为返回的相对路径格式。
  3. 下载文件逻辑:在 downloadAndSaveFile 方法中,通过创建一个 URL 连接,打开连接并获取文件流。然后使用输入流和输出流将文件保存到本地指定的目录中,生成新的文件名以避免冲突。

  4. 生成保存路径:使用当前日期和时间生成保存文件的路径,包括年、月和日的子目录。

  5. 转换返回路径:将保存的文件路径转换为相对于默认路径 /profile 的相对路径格式。

  6. 获取当前时间戳:通过 getCurrentTimestamp 方法获取当前时间的时间戳,精确到秒,用于生成带时间戳的文件名。

具体使用

很简单,直接调用即可!!!

@GetMapping("/download")
    public AjaxResult downloadFilebyUrl(@RequestParam String url, @RequestParam String fielName) {
        String path = FileUtils.downloadAndSaveFile(url, fielName);
        if (StringUtils.isNotBlank(path)) {
            return AjaxResult.success(path);
        } else {
            return AjaxResult.error("文件下载失败!!!");
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT小辉同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值