一、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/n/183117.html
微信扫一扫
支付宝扫一扫