springboot实现文件上传的代码实现
时间: 2023-08-05 13:22:04 浏览: 118
spring boot 实现文件上传
好的,以下是Spring Boot实现文件上传的代码实现:
1. 首先需要在pom.xml中引入文件上传相关依赖,如下:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 文件上传依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
```
2. 在Controller中添加上传文件的接口方法,如下:
```java
@RestController
@RequestMapping("/file")
public class FileUploadController {
@Autowired
private FileStorageService fileStorageService;
@PostMapping("/upload")
public Response upload(@RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/file/download/")
.path(fileName)
.toUriString();
return new Response(true, "File uploaded successfully", new FileInfo(fileName, fileDownloadUri, file.getContentType(), file.getSize()));
}
}
```
3. 在Service中添加文件存储的方法,如下:
```java
@Service
public class FileStorageService {
@Value("${file.upload-dir}")
private String uploadDir;
public String storeFile(MultipartFile file) {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
if (fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
Path targetLocation = Paths.get(uploadDir + "/" + fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
}
}
```
其中,${file.upload-dir}是在application.properties中配置的文件上传路径。
4. 最后在application.properties中添加文件上传路径的配置,如下:
```properties
file.upload-dir=/path/to/upload/directory
```
以上就是Spring Boot实现文件上传的代码实现。
阅读全文