简体   繁体   English

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

[英]Auto Upload functionality in spring boot and Ajax

We have one of the banking project where we have requirement where we have to upload the file at the time of uploading It self (means Autoupload) How to use Ajax call for auto upload using spring boot, 我们有一个银行业务项目,其中有一个要求,我们必须在上传文件时自行上传文件(即自动上传),如何使用Ajax调用通过Spring Boot自动上传,

This is the Spring boot Controller I have - 这是我拥有的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";
    }

I have in input file field like this 我在这样的输入文件字段中

<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>

Here is the I find and this resolve the issue of this problem and I find which is very useful for this problem of auto uploading at the time of uplaoding time itself. 这是我找到的,并且可以解决此问题的问题,我发现这对于在更新时间本身时自动上传的问题非常有用。 please check this out 请检查一下

$('#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);
}


});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM