在Spring Boot中实现文件上传与管理
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@Service
public class FileUploadService {
private final Path fileStorageLocation = Paths.get("uploads");
@Autowired
private StorageService storageService;
public String storeFile(MultipartFile file) {
// 确保服务器存储路径存在
try {
Files.createDirectories(fileStorageLocation);
// 获取文件原始名字
String filename = file.getOriginalFilename();
// 保存文件
Path filePath = this.fileStorageLocation.resolve(filename);
Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
// 存储文件信息到数据库或其他存储
storageService.store(filePath.toString());
return filename;
} catch (Exception e) {
throw new RuntimeException("Could not store the file. Error: " + e.getMessage(), e);
}
}
public Resource loadFileAsResource(String filename) {
try {
Path filePath = this.fileStorageLocation.resolve(filename);
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new RuntimeException("Could not read the file.");
}
} catch (MalformedURLException e) {
throw new RuntimeException("Error: " + e.getMessage(), e);
}
}
public void deleteAll() {
FileSystemUtils.deleteRecursively(fileStorageLocation.toFile());
}
}
这个代码示例展示了如何在Spring Boot应用中实现文件的
评论已关闭