import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,因为文件为空";
}
try {
// 保存文件到指定路径
byte[] bytes = file.getBytes();
Path path = Paths.get("uploads/" + file.getOriginalFilename());
Files.write(path, bytes);
return "上传成功: " + file.getOriginalFilename();
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
}
}
MultipartFile类来处理文件上传。MultipartFile是Spring提供的一个接口,用于封装上传的文件。FileUploadController是一个Spring MVC控制器,用于处理HTTP POST请求。@RestController:表示这是一个RESTful风格的控制器。@PostMapping("/upload"):表示这个方法会处理POST请求,路径为/upload。@RequestParam("file") MultipartFile file:表示从请求参数中获取名为file的文件。file.getBytes()获取文件的字节数组。Files.write()将文件保存到服务器的uploads目录下。希望这段代码和解释对你有帮助!
下一篇:java.util.date
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站