struct spring前后端未分离项目 上传文件到后端代码示例
时间: 2023-05-31 07:04:21 浏览: 64
以下是一个上传文件到后端的代码示例,使用Spring MVC框架:
@Controller
@RequestMapping("/file")
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:/";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get("/uploads/" + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/";
}
}
在上面的示例中,我们使用了@RequestParam注释来接收文件,如果文件不存在或为空,我们将重定向到主页,并在重定向时添加一个消息。如果文件存在,我们将读取它的字节,将其写入指定的路径,并在重定向时添加一个消息来确认文件已成功上传。