用户springboot写一个文件上传的代码
时间: 2023-05-23 15:07:41 浏览: 94
好的,这里是一个简单的Spring Boot文件上传的代码:
```java
@RestController
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
// Check if file is empty
if (file.isEmpty()) {
return new ResponseEntity<>("Please select a file to upload", HttpStatus.BAD_REQUEST);
}
// Get the file name and extension
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
String fileExtension = fileName.substring(fileName.lastIndexOf("."));
// Save the file to the local file system
try {
String savePath = "C:/uploads/";
File uploadDir = new File(savePath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
String uploadFilePath = savePath + fileName;
File dest = new File(uploadFilePath);
file.transferTo(dest);
} catch (IOException e) {
return new ResponseEntity<>("Failed to upload file", HttpStatus.INTERNAL_SERVER_ERROR);
}
// Return success
return ResponseEntity.ok("File uploaded successfully");
}
}
```
这个控制器基于RESTful架构,使用了`@PostMapping`注释匹配POST请求(在这个例子中,是`/upload`)。它所做的就是接收一个文件(`@RequestParam`注释指定了这个参数的名字为`file`),检查文件是否为空,保存这个文件到本地文件系统然后返回一个成功信息。
如果上传成功,响应将会是以下内容:
```json
{
"status": 200,
"message": "File uploaded successfully"
}
```
当发生错误时(比如说,上传一个空文件),响应将会是以下内容:
```json
{
"status": 400,
"message": "Please select a file to upload"
}
```
阅读全文