Java downloads files through file stream and file address

insert image description here

Download files via FileStream

How to use MultipartFileto upload files, download them locally, and return the save path:

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;
    }
}

It is used to obtain the file stream in the Spring Boot application, then process the uploaded file, save the file to the specified directory and return the saved file path. Here is a brief description of each part of the code:

  1. Upload directory settings : In this example, UPLOAD_DIRconstants are used to define the directory path for uploading files. You need to modify this to the path where you actually want your uploaded files to be saved.

  2. Save the file and get the path : saveFileAndGetPathThe method receives an MultipartFileobject representing the uploaded file. In this method, save the uploaded file to the specified directory and return the saved file path.

  3. generate_filename : generateFileNamemethod is used to generate a new filename with a timestamp to avoid filename collisions. It uses a timestamp of the current time (accurate to the second) as part of the filename and preserves the extension of the original filename.

  4. Upload logic : In saveFileAndGetPaththe method, use MultipartFilethe input stream of the object to read the content of the uploaded file, and write the content to the specified file path through the output stream.

Download files by file address

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);
    }
}

It is used to process file download, save and path conversion operations according to the file URL address. Here is a brief description of each part of the code:

  1. Import and Logging : Required classes and packages are imported, and @Slf4jannotations are used to automatically generate logging code.

  2. Default paths and methods :

    • defaultBaseDir: The default file save path, RuoYiConfig.getProfile()obtained through the method, you need to set it as the actual file save directory.
    • downloadAndSaveFile(String url, String originalFileName): Download the file and save it locally, receiving the URL of the file and the original file name as parameters.
    • generateFileNameWithTimestamp(String originalFileName): Generate a new filename with a timestamp based on the original filename.
    • generateSavePath(String fileName): Generate the saved file path according to the file name, including subdirectories of year, month, and day.
    • convertToReturnPath(String filePath): Convert the file path to the returned relative path format.
  3. Download file logic : In downloadAndSaveFilethe method, by creating a URL connection, open the connection and get the file stream. Then use the input stream and output stream to save the file to the specified directory locally, generating a new file name to avoid conflicts.

  4. Generate Save Path : Use the current date and time to generate a save file path, including year, month, and day subdirectories.

  5. Convert Return Path : Convert the saved file path to a /profilerelative path format relative to the default path.

  6. Get the current timestamp : getCurrentTimestampGet the timestamp of the current time through the method, accurate to seconds, and use it to generate a file name with a timestamp.

Specific use

It's very simple, just call it directly! ! !

@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("文件下载失败!!!");
        }
    }

Guess you like

Origin blog.csdn.net/weixin_53742691/article/details/132287943