一、Springboot接收文件流
在Springboot中,接收文件的方法有多種,其中一種是通過接收文件流的方式。我們可以通過 使用MultipartFile來處理文件上傳的請求並獲得流對象,然後對流對象進行操作。
@PostMapping("/upload")
public void uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 獲取文件輸入流
InputStream inputStream = file.getInputStream();
// 對文件流進行操作
// ...
} catch (IOException e) {
e.printStackTrace();
}
}
這裡我們通過MultipartFile的getInputStream()方法可以獲取到文件的輸入流對象,通過這個對象我們就可以對文件進行操作。
二、Springboot接受文件上傳
Springboot可以通過使用MultipartFile自動處理文件上傳的請求,並將其保存至指定路徑。在此之前,你需要在application.yml文件中進行以下配置,定義上傳文件的大小和上傳文件的最大大小。
spring.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB
在controller中使用@RequestPart註解即可處理上傳請求,同時定義文件的保存路徑,如下:
@PostMapping(value = "/fileUpload")
public String uploadFile(@RequestPart("file") MultipartFile file) throws IOException {
long timestamp = Instant.now().toEpochMilli();
String filePath = "/opt/data/upload/" + timestamp + "_" + file.getOriginalFilename();
file.transferTo(new File(filePath));
return "success";
}
三、Springboot接收文件並解析
在Springboot中,我們可以使用Apache POI技術對Excel數據進行解析。
首先在pom.xml中添加Apache POI相關的依賴, 如下:
org.apache.poi
poi-ooxml
5.1.0
然後,在controller中使用MultipartFile接收文件,然後採用以下代碼進行解析Excel數據。
@PostMapping(value = "/uploadExcel")
public String uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
Workbook workbook = WorkbookFactory.create(file.getInputStream());
Sheet sheet = workbook.getSheetAt(0);
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
// 處理excel數據
// ...
}
return "success";
}
四、Springboot接收文件的標籤
在Springboot中,可以使用標籤和輸入框來接收文件。 示例如下:
五、Springboot接收圖片
Springboot通過流式編程可以處理圖片上傳與下載,可以通過定義一個Dto類來接受圖片,並且採用Base64位表達式編碼方案進行存儲到資料庫中。 示例如下:
@Setter
@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class ImageUploadDto {
private String imageHeader;
private String imageData;
}
@PostMapping(value = "/image/upload", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<FpResponse> upload(@RequestBody ImageUploadDto dto) {
try {
String fileName = UUID.randomUUID().toString() + new Date().getTime() + ".png";
String savePath = QiniuFileUtils.uploadBase64Image(fileName, dto.getImageData());
// 返回結果
return ResponseEntity.ok().body(FpResponse.success(true));
} catch (Exception e) {
// 返回錯誤信息
return ResponseEntity.badRequest().body(FpResponse.error("上傳失敗"));
}
}
六、Springboot接收文件並保存
Springboot可以把文件保存到本地或者第三方存儲(如:阿里雲、七牛雲)中。你可以在controller中使用MultipartFile和File相關的代碼塊去處理文件上傳請求。 示例如下:
@PostMapping(value = "/upload")
public String upload(@RequestParam(value = "file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
throw new IllegalStateException("File is empty");
}
String fileName = file.getOriginalFilename();
String extension = FilenameUtils.getExtension(fileName);
String filePath = "/opt/data/upload/" + System.currentTimeMillis() + "." + extension;
File dest = new File(filePath);
file.transferTo(dest);
return "success";
}
七、Springboot配置文件
要啟用Springboot的文件上傳和下載功能,在applications.yml文件中配置multipart文件解析器。 示例如下:
spring:
servlet:
multipart:
enabled: true
max-file-size: 5MB // 最大文件
max-request-size: 5MB // 最大請求
# 列印sql
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
八、Springboot文件上傳
在Springboot中,你可以通過以下代碼完成文件上傳,以下代碼中method代表上傳的方法,file代表上傳的文件,filePath代表文件上傳的路徑。 示例如下:
public String uploadFile(String method, MultipartFile file, String filePath) {
OutputStream out;
InputStream is;
String uploadUrl = baseUrl + method;
try {
String fileName = file.getOriginalFilename();
is = file.getInputStream();
byte[] content = new byte[is.available()];
is.read(content);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("filename", fileName);
HttpEntity fileEntity = new HttpEntity(content, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity response = restTemplate.exchange(uploadUrl, HttpMethod.POST,
new HttpEntity(fileEntity, headers), String.class);
if (response.getStatusCode() == HttpStatus.OK) {
return "success";
}
} catch (Exception e) {
e.printStackTrace();
}
return "fail";
}
九、Springboot文件下載
Springboot具備文件的下載功能,主要需要採用ResponseEntity返回結果,如下:
@GetMapping(value = "/download")
public ResponseEntity download(HttpServletRequest request, HttpServletResponse response) throws IOException {
byte[] data = null;
File file = new File("文件路徑");
try (InputStream inputStream = new FileInputStream(file)) {
data = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
log.error("下載文件失敗", e);
}
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + file.getName());
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity responseEntity = new ResponseEntity(data, headers, statusCode);
return responseEntity;
}
總結
本文主要講解了Springboot接收文件流、文件上傳、文件解析、文件標籤、圖片上傳、文件保存、配置文件、文件上傳和文件下載的相關知識點,希望對大家有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/183117.html
微信掃一掃
支付寶掃一掃