Sử dụng MultipartFile
Chuẩn bị biểu mẫu
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
Tập tin:<input type="file" name="anh_dai_dien"/>
Tên:<input type="text" name="ten"/>
<input type="submit" value="Tải lên"/>
</form>
</body><br></br>
Bộ điều khiển
import net.xdclass.demo.domain.JsonData;
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 javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@RestController
public class TaiLenFileController {
private static final String duongDanLuu = "D:\\IdeaProjects\\xdclass_springboot\\src\\main\\resources\\static\\anh\\";
@PostMapping(value = "/upload")
public JsonData xuLyTaiLen(
@RequestParam(value = "anh_dai_dien") MultipartFile tapTin,
HttpServletRequest request) {
// Thuộc tính name="ten" của biểu mẫu
String tenNguoiDung = request.getParameter("ten");
// Tên tập tin được tải lên
String tenTepTin = tapTin.getOriginalFilename();
String tenMoi = tenTepTin.substring(tenTepTin.lastIndexOf("."));
// Tạo ngẫu nhiên
tenTepTin = UUID.randomUUID() + tenMoi;
File dich = new File(duongDanLuu + tenTepTin);
try {
tapTin.transferTo(dich);
return new JsonData(0, dich);
} catch (IOException e) {
e.printStackTrace();
}
return new JsonData(-1, null, "lỗi khi lưu");
}
}
Phương thức transferTo của đối tượng MultipartFile được sử dụng để lưu tập tin (độ hiệu quả và thao tác tiện lợi hơn so với cách dùng FileOutStream trước đây).
Truy cập http://localhost:8080/upload.html, kết quả như sau.
{
"code": 0,
"data": "D:\\IdeaProjects\\xdclass_springboot\\src\\main\\resources\\static\\anh\\611fbdd7-95c5-4803-8c6f-796cccf6d2be.jpg",
"msg": null
}
Xem ảnh đã tải lên.
http://localhost:8080/anh/611fbdd7-95c5-4803-8c6f-796cccf6d2be.jpg
Xem xét 1: Giới hạn kích thước tập tin
Ý tưởng: Tạo createMultipartConfig tùy chỉnh. Có thể đặt trong lớp khởi chạy.
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// Kích thước tối đa của một tập tin
factory.setMaxFileSize(DataSize.ofMegabytes(300));
/// Đặt tổng kích thước dữ liệu tải lên
factory.setMaxRequestSize(DataSize.ofGigabytes(1));
return factory.createMultipartConfig();
}
Xem xét 2: Tùy chỉnh đường dẫn lưu tập tin tải lên
Tránh mã hóa cứng, ý tưởng: Viết vào tệp cấu hình, đọc ra.
Tham khảo bài viết "Đọc tệp cấu hình" của tôi, https://www.cnblogs.com/wuyicode/p/11249913.html .