springboot上传文件接口
时间: 2023-10-09 15:05:31 浏览: 119
你可以使用Spring Boot来创建一个文件上传的接口。下面是一个示例代码:
首先,需要添加以下依赖到你的pom.xml文件中:
```xml
<dependencies>
<!-- 其他依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
```
然后创建一个Controller类,处理上传文件的请求:
```java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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 java.io.File;
import java.io.IOException;
@RestController
public class FileUploadController {
@Value("${upload-dir}")
private String uploadDir;
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return new ResponseEntity<>("Please select a file to upload", HttpStatus.BAD_REQUEST);
}
try {
String fileName = file.getOriginalFilename();
String filePath = uploadDir + File.separator + fileName;
file.transferTo(new File(filePath));
return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
} catch (IOException e) {
return new ResponseEntity<>("Failed to upload file",
阅读全文