为了账号安全,请及时绑定邮箱和手机立即绑定

Spring Boot和Ajax中的自动上传功能

Spring Boot和Ajax中的自动上传功能

HUH函数 2021-04-12 14:19:19
我们有一个银行项目,要求在上传文件时必须在其中上传文件本身(意味着自动上传),如何使用Ajax调用来使用Spring Boot自动上传,这是我拥有的Spring Boot Controller-@Controllerpublic 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>
查看完整描述

1 回答

?
繁花不似锦

TA贡献1851条经验 获得超4个赞

这是我找到的,并且可以解决此问题的问题,我发现这对于在更新时间本身时自动上传的问题非常有用。请检查一下


$('#certificate_document_other').on("change",function(){

 var objFormData=new FormData();// to capture all form form information inform of object

 var objFile= $(this)[0].files[0];

 objFormData.append('file',objFile);

 $.ajax({

   url:"/SomeProjetName/fileUpload",

   type: "POST",

   enctype:"multipart/form-data",

   data:objFormData,

   contentType:false,

   processType:false,

   success: function(data){

      alert('upload SuccessFull');


},error:function(xhr,status,errorType){

    alert(xhr.status);

    alert(xhr.responseText);

}



});

});


查看完整回答
反对 回复 2021-04-21
  • 1 回答
  • 0 关注
  • 144 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信