一、SpringBoot上傳文件到資料庫
文件上傳到資料庫是一個常見的需求,可以用於保存用戶上傳的圖片等二進位文件。在SpringBoot中,使用Spring提供的Hibernate框架,配合Spring的JdbcTemplate實現文件上傳到資料庫。
首先,需要定義資料庫表來存儲上傳的文件信息,包括文件ID,文件名,文件類型,文件大小和文件內容等欄位。創建對應的Java類,並添加註解來映射資料庫表和欄位:
@Entity
@Table(name = "t_file")
public class File {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; //文件ID
@Column(name = "file_name")
private String fileName; //文件名
@Column(name = "file_type")
private String fileType; //文件類型
@Column(name = "file_size")
private Long fileSize; //文件大小
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "file_content")
private byte[] fileContent; //文件內容
//省略get/set方法
}
接下來,編寫控制器來實現文件上傳到資料庫。使用Spring的MultipartFile介面來處理上傳的文件,通過JdbcTemplate來將文件信息存儲到資料庫。代碼如下:
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
private JdbcTemplate jdbcTemplate;
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String fileType = file.getContentType();
Long fileSize = file.getSize();
byte[] fileContent = file.getBytes();
String sql = "INSERT INTO t_file (file_name, file_type, file_size, file_content) VALUES (?, ?, ?, ?)";
jdbcTemplate.update(sql, fileName, fileType, fileSize, fileContent);
return "file uploaded successfully";
}
}
在瀏覽器中訪問http://localhost:8080/file/upload,上傳文件即可保存到資料庫中。這樣就實現了上傳文件到資料庫的功能。
二、SpringBoot上傳文件和參數
在實際開發中,文件上傳往往需要與其他表單數據一起提交,比如上傳用戶頭像時,還需要同時提交用戶名和密碼等信息。SpringBoot也支持同時上傳文件和參數。
可以使用@RequestParam註解來獲取上傳的文件和表單參數,示例代碼如下:
@PostMapping("/uploadWithParam")
public String uploadWithParam(@RequestParam("file") MultipartFile file, @RequestParam("username") String username, @RequestParam("password") String password) throws IOException {
String fileName = file.getOriginalFilename();
String fileType = file.getContentType();
Long fileSize = file.getSize();
byte[] fileContent = file.getBytes();
//保存文件到資料庫或伺服器
//省略代碼
return "file uploaded successfully with user "+username+" and password "+password;
}
在瀏覽器中訪問http://localhost:8080/file/uploadWithParam,同時上傳文件和參數即可。
三、SpringBoot多線程上傳文件
當上傳的文件較大時,可能需要較長時間才能完成上傳。為了提高上傳效率,可以使用多線程技術來實現文件的分塊上傳。SpringBoot也支持多線程上傳文件。
可以使用Java的Executor框架來創建線程池,將文件分塊後,將每一塊交給線程池中的線程處理。當所有線程都執行完畢後,將文件塊合併成完整的文件。示例代碼如下:
@PostMapping("/uploadMultiThread")
public String uploadMultiThread(@RequestParam("file") MultipartFile file) throws IOException, ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(3);
String fileName = file.getOriginalFilename();
String fileType = file.getContentType();
Long fileSize = file.getSize();
byte[] fileContent = file.getBytes();
int chunkSize = 1024*1024; //每個線程上傳1MB的數據
int numChunks = (int)Math.ceil(fileSize/chunkSize); //計算要上傳的線程數
List<Future> futures = new ArrayList();
for (int i = 0; i < numChunks; i++) {
int startIndex = i*chunkSize;
int endIndex = Math.min(startIndex+chunkSize, (int)fileSize);
byte[] subFileContent = Arrays.copyOfRange(fileContent, startIndex, endIndex);
futures.add(executor.submit(new FileUploadTask(i, subFileContent)));
}
List results = new ArrayList();
for (Future future : futures) {
results.add(future.get());
}
executor.shutdown();
//將所有分塊合併為完整的文件,並保存到資料庫或伺服器
//省略代碼
return "file uploaded successfully with multi-threading";
}
private class FileUploadTask implements Callable {
private int index;
private byte[] fileContent;
public FileUploadTask(int index, byte[] fileContent) {
this.index = index;
this.fileContent = fileContent;
}
@Override
public String call() throws Exception {
//上傳分塊文件
//省略代碼
return "chunk "+index+" uploaded successfully";
}
}
在瀏覽器中訪問http://localhost:8080/file/uploadMultiThread,啟動多線程上傳文件。
四、SpringBoot上傳文件到指定文件夾
有時候,需要將上傳的文件保存到指定的文件夾中。SpringBoot提供了文件系統相關的API來實現上傳文件到指定文件夾。
可以使用Spring的Resource介面以及Java的File類來指定存儲文件的文件夾。示例代碼如下:
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${upload.path}") //從配置文件中讀取文件夾路徑
private String uploadPath;
@PostMapping("/uploadToFile")
public String uploadToFile(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String fileType = file.getContentType();
Long fileSize = file.getSize();
byte[] fileContent = file.getBytes();
File folder = new File(uploadPath);
if (!folder.exists()) {
folder.mkdirs(); //如果文件夾不存在,則創建文件夾
}
Path filePath = Paths.get(uploadPath, fileName);
Files.write(filePath, fileContent);
return "file uploaded successfully to "+uploadPath;
}
}
在配置文件application.yml中添加文件夾路徑:
upload: path: /tmp/upload
在瀏覽器中訪問http://localhost:8080/file/uploadToFile,上傳的文件即可保存到指定文件夾中。
五、SpringBoot非同步上傳文件
非同步上傳文件可以提高網站的性能和響應速度,由於上傳操作會耗費一定時間,非同步上傳可以讓伺服器在上傳過程中處理其他請求,提升系統的並發處理能力。SpringBoot提供了非同步上傳文件的API。
可以使用Spring的@Async註解來將上傳文件的方法標記為非同步執行。示例代碼如下:
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
private AsyncFileUploader asyncFileUploader;
@PostMapping("/uploadAsync")
public String uploadAsync(@RequestParam("file") MultipartFile file) {
String fileName = file.getOriginalFilename();
String fileType = file.getContentType();
Long fileSize = file.getSize();
byte[] fileContent = null;
try {
fileContent = file.getBytes();
} catch (IOException e) {
e.printStackTrace();
}
asyncFileUploader.upload(fileName, fileType, fileSize, fileContent);
return "file uploaded asynchronously";
}
}
@Service
public class AsyncFileUploader {
@Async
public void upload(String fileName, String fileType, Long fileSize, byte[] fileContent) {
//上傳文件
//省略代碼
}
}
在瀏覽器中訪問http://localhost:8080/file/uploadAsync,上傳文件即可非同步上傳。
六、SpringBoot上傳文件和圖片
上傳圖片是網站開發中的一個常見需求,SpringBoot也支持上傳圖片。可以通過修改前面的上傳文件的代碼,在上傳文件時添加圖片壓縮等處理邏輯,實現上傳圖片的功能。
例如,可以使用Java的ImageIO類來將上傳的圖片進行壓縮和縮放,代碼如下:
@PostMapping("/uploadImage")
public String uploadImage(@RequestParam("image") MultipartFile image) throws IOException {
String imageName = image.getOriginalFilename();
String imageType = image.getContentType();
Long imageSize = image.getSize();
byte[] imageContent = image.getBytes();
//壓縮和縮放圖片
BufferedImage bufferedImage = ImageIO.read(image.getInputStream());
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if (width > 1024 || height > 1024) {
float scale = Math.min(1024f/width, 1024f/height);
width = (int)(width*scale);
height = (int)(height*scale);
}
Image scaledImage = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(scaledImage, 0, 0, null);
g2d.dispose();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(resizedImage, "JPEG", outputStream);
imageContent = outputStream.toByteArray();
//保存圖片到資料庫或伺服器
//省略代碼
return "image uploaded successfully";
}
在瀏覽器中訪問http://localhost:8080/file/uploadImage,上傳圖片即可實現上傳圖片的功能。
七、SpringBoot批量上傳文件
有時候,需要同時上傳多個文件,SpringBoot也支持批量上傳文件。可以使用Spring的MultipartHttpServletRequest類來獲取所有上傳的文件,然後逐個保存到資料庫或伺服器。示例代碼如下:
@PostMapping("/uploadBatch")
public String uploadBatch(HttpServletRequest request) throws IOException {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator iterator = multiRequest.getFileNames();
while (iterator.hasNext()) {
MultipartFile file = multiRequest.getFile(iterator.next());
String fileName = file.getOriginalFilename();
String fileType = file.getContentType();
Long fileSize = file.getSize();
byte[] fileContent = file.getBytes();
//保存文件到資料庫或伺服器
//省略代碼
}
return "batch uploaded successfully";
}
在瀏覽器中訪問http://localhost:8080/file/uploadBatch,同時上傳多個文件即可實現批量上傳文件的功能。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/151319.html
微信掃一掃
支付寶掃一掃