Download files via FileStream
How to use MultipartFile
to 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:
-
Upload directory settings : In this example,
UPLOAD_DIR
constants 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. -
Save the file and get the path :
saveFileAndGetPath
The method receives anMultipartFile
object representing the uploaded file. In this method, save the uploaded file to the specified directory and return the saved file path. -
generate_filename :
generateFileName
method 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. -
Upload logic : In
saveFileAndGetPath
the method, useMultipartFile
the 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:
-
Import and Logging : Required classes and packages are imported, and
@Slf4j
annotations are used to automatically generate logging code. -
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.
-
Download file logic : In
downloadAndSaveFile
the 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. -
Generate Save Path : Use the current date and time to generate a save file path, including year, month, and day subdirectories.
-
Convert Return Path : Convert the saved file path to a
/profile
relative path format relative to the default path. -
Get the current timestamp :
getCurrentTimestamp
Get 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("文件下载失败!!!");
}
}