【发布时间】:2018-12-02 13:31:22
【问题描述】:
我们有一个银行项目,我们需要在上传文件时自行上传文件(意味着自动上传) 如何使用spring boot使用Ajax调用进行自动上传,
这是我拥有的 Spring Boot Controller -
@Controller
public class UploadController {
//Save the uploaded file to this folder
private static String UPLOADED_FOLDER = "F://temp//";
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("/upload") // //new annotation since 4.3
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
我有这样的输入文件字段
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
【问题讨论】:
-
您尝试过什么来实现这一目标?显然,你需要一些 JS 代码,并且使用谷歌查找示例应该相当简单
标签: java ajax spring spring-mvc spring-boot