List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
if (!file.isEmpty()) {
}
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@RestController // 如果是API接口,使用@RestController;如果是处理视图,则使用@Controller
public class FileUploadController {
@Autowired
private FileStorageService fileStorageService; // 假设有一个用于处理文件存储的服务
@PostMapping("/upload-multiple")
public String handleFileUpload(@RequestParam("files") MultipartFile[] files, RedirectAttributes redirectAttributes) {
List<String> savedFilesPaths = new ArrayList<>();
for (MultipartFile file : files) {
if (!file.isEmpty()) {
try {
String storedFilePath = fileStorageService.store(file); // 调用服务类的方法来存储文件并返回路径
savedFilesPaths.add(storedFilePath);
} catch (IOException e) {
// 处理文件上传失败的情况
e.printStackTrace();
redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " due to " + e.getMessage());
}
} else {
redirectAttributes.addFlashAttribute("message", "Failed to upload empty file " + file.getOriginalFilename());
}
}
// 将已成功上传并存储的文件路径添加到集合中,这里直接返回或用于后续业务逻辑
return "Successfully uploaded: " + savedFilesPaths;
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class FileStorageService {
private final Path fileStorageLocation; // 文件存储位置,需要在配置类中注入
@Autowired
public FileStorageService(FileStorageProperties properties) {
this.fileStorageLocation = Paths.get(properties.getLocation());
}
public String store(MultipartFile file) throws IOException {
// 创建文件名(可以自定义生成策略)
Path targetLocation = this.fileStorageLocation.resolve(file.getOriginalFilename());
// 保存文件
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
// 返回存储路径
return targetLocation.toString();
}
}
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ResourcesConfig implements WebMvcConfigurer{
@Value("${filestorage.location}")
private String fileURl;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
/** 通过url访问项目外的目录图片*/
registry.addResourceHandler("/cert/**").addResourceLocations("file:/D:/load/img/");
}
}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class StorageConfiguration {
@Bean
public FileStorageProperties fileStorageProperties() {
return new FileStorageProperties();
}
}
@ConfigurationProperties(prefix = "filestorage")
class FileStorageProperties {
private String location = "upload-dir";
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
application.properties
filestorage.location=/path/to/your/upload/folder
单文件上传
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("Please select a file to upload.");
}
try {
// 保存文件到服务器指定目录
Path filePath = Paths.get("/" + file.getOriginalFilename());
Files.copy(file.getInputStream(), filePath);//FileUtils.copyInputStreamToFile(source, destination);
//或者file.transferTo(dest);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getOriginalFilename() + "\"")
.body("Successfully uploaded - " + file.getOriginalFilename());
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Failed to store file: " + e.getMessage());
}
}
大文件分块下载
package com.rui;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
public class FileChunkingAndMergingTest {
private static final int CHUNK_SIZE = 1024 * 1024; // 假设每个块大小为1MB
public static void main(String[] args) throws IOException {
String sourceFilePath = "D:\\apache-tomcat-8.5.75.zip"; // 大文件路径
String tempDirectoryPath = "C:\\abc"; // 临时目录用于存放分块
String targetFilePath = "C:\\abc\\merged-tomcat.zip"; // 合并后的文件路径
// 分割文件到临时目录
List<String> chunkFiles = splitFile(sourceFilePath, tempDirectoryPath, CHUNK_SIZE);
// 合并分块文件到目标文件
mergeChunks(chunkFiles, targetFilePath);
System.out.println("File has been successfully split and merged.");
}
/**
* 将大文件分割成多个小文件,并将各个分块文件路径存入列表返回。
*/
public static List<String> splitFile(String sourceFilePath, String tempDirectoryPath, int chunkSize) throws IOException {
File sourceFile = new File(sourceFilePath);
File tempDir = new File(tempDirectoryPath);
if (!tempDir.exists() && !tempDir.mkdirs()) {
throw new IOException("Failed to create temporary directory: " + tempDirectoryPath);
}
List<String> chunkFilePaths = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(sourceFile);
FileChannel fileChannel = fis.getChannel()) {
long fileSize = fileChannel.size();
for (long position = 0; position < fileSize; position += chunkSize) {
long remainingFileSize = fileSize - position;
long chunkEnd = Math.min(position + chunkSize - 1, fileSize - 1);
String chunkFileName = "chunk-" + position + ".part";
File chunkFile = new File(tempDirectoryPath, chunkFileName);
try (FileOutputStream fos = new FileOutputStream(chunkFile);
FileChannel outChannel = fos.getChannel()) {
fileChannel.transferTo(position, Math.min(chunkSize, remainingFileSize), outChannel);
}
chunkFilePaths.add(chunkFile.getAbsolutePath());
}
}
return chunkFilePaths;
}
/**
* 将多个分块文件按顺序合并到目标文件。
*/
public static void mergeChunks(List<String> chunkFilePaths, String targetFilePath) throws IOException {
File targetFile = new File(targetFilePath);
try (FileOutputStream fos = new FileOutputStream(targetFile)) {
FileChannel outChannel = fos.getChannel();
for (String chunkFilePath : chunkFilePaths) {
File chunkFile = new File(chunkFilePath);
try (FileInputStream fis = new FileInputStream(chunkFile);
FileChannel inChannel = fis.getChannel()) {
inChannel.transferTo(0, inChannel.size(), outChannel);
}finally {
// 在每次成功转移数据后删除分块文件
if (!chunkFile.delete()) {
System.err.println("Failed to delete the chunk file: " + chunkFilePath);
}
}
}
}
// 确保所有分块都已成功合并并删除,这里可以进行额外的清理操作
// for (String chunkFilePath : chunkFilePaths) {
// File chunkFile = new File(chunkFilePath);
// if (chunkFile.exists() && !chunkFile.delete()) { // 如果由于某种原因之前未删除,再次尝试删除
// FileUtils.deleteQuietly(chunkFile);
// System.err.println("Final attempt to delete the chunk file failed: " + chunkFilePath);
// }
// }
}
}
普通下载
@GetMapping("/download/stream/{filename}")
public ResponseEntity<StreamingResponseBody> streamDownload(@PathVariable String filename) throws IOException {
File file = new File("C:\\abc\\merged-tomcat.zip");
if (!file.exists()) {
return ResponseEntity.notFound().build();
}
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"");
StreamingResponseBody streamingBody = outputStream -> {
try (InputStream inputStream = new FileInputStream(file)) {
byte[] buffer = new byte[4096]; // 假设每次读取4KB
int n;
while ((n = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, n);
}
} catch (IOException ex) {
throw new RuntimeException("IO Error writing to output stream", ex);
}
};
ResponseEntity<StreamingResponseBody> responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(streamingBody);
return responseEntity;
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/200893.html