简体   繁体   中英

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,

This is the Spring boot Controller I have -

@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);
}


});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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