如何在Spring Boot中实现文件上传和下载功能 如何在Spring Boot中实现文件上传和下载功能?
在Spring Boot中实现文件上传和下载功能可以通过以下步骤完成:
文件上传:
在Spring Boot应用中添加一个文件上传的POST接口。
在Controller中使用@RequestParam("file")
注解来接收上传的文件。
在Controller中使用MultipartFile
类型来接收文件对象。
使用file.transferTo(new File(filePath))
将文件保存到指定路径。
文件下载:
在Spring Boot应用中添加一个文件下载的GET接口。
使用@PathVariable
注解将文件名作为路径参数。
使用ResponseEntity
作为返回类型,并设置响应头Content-Disposition
为attachment; filename=<文件名>
来表示为下载文件。
使用FileInputStream
将文件读取为字节流。
使用ByteArrayResource
将字节数组封装为资源对象,并返回ResponseEntity.ok().contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource)
来进行文件下载。
下面是一个简单的示例:
文件上传的Controller:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
String filePath = "/path/to/save/" + file.getOriginalFilename();
file.transferTo(new File(filePath));
return "redirect:/success";
} catch (Exception e) {
return "redirect:/error";
}
}
}
文件下载的Controller:
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@Controller
public class FileDownloadController {
@GetMapping("/download/{filename}")
public ResponseEntity<Object> downloadFile(@PathVariable String filename) {
String filePath = "/path/to/files/" + filename;
File file = new File(filePath);
try {
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
ByteArrayResource resource = new ByteArrayResource(data);
return ResponseEntity.ok().contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error downloading file");
}
}
}
需要注意的是,上述示例中的路径、请求路径以及异常处理等需要根据实际需求进行适当调整。
【以下回答由 ChatGPT 生成】
在项目的pom.xml
文件中添加以下依赖:
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot 上传文件支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
// 检查并处理上传的文件
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// 处理文件逻辑
return "文件上传成功!";
} catch (IOException e) {
e.printStackTrace();
return "文件上传失败!";
}
} else {
return "请选择要上传的文件!";
}
}
}
在上面的代码中,我们使用@PostMapping
注解来处理上传文件的POST请求,并通过@RequestParam("file")
注解来接收文件参数。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>
在上面的代码中,我们使用enctype="multipart/form-data"
来指定表单支持文件上传。
http://localhost:8080/fileupload.html
即可上传文件。在项目的pom.xml
文件中添加以下依赖:
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
@RestController
public class FileDownloadController {
@GetMapping("/download")
public void handleFileDownload(HttpServletResponse response) {
// 设置文件下载信息
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"filename.txt\"");
try {
// 读取文件内容并写入到response中
byte[] data = "This is the content of the file.".getBytes();
response.getOutputStream().write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上述代码中,我们使用@GetMapping
注解来处理文件下载的GET请求,并设置Content-Disposition
头文件以指定文件名。
http://localhost:8080/download
即可下载文件。以上是一个基本的示例,你可以根据自己的业务需求进行进一步的扩展和优化。
【相关推荐】