【问题标题】:Auto Upload functionality in spring boot and AjaxSpring Boot 和 Ajax 中的自动上传功能
【发布时间】: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


【解决方案1】:

这是我发现的,这解决了这个问题,我发现这对于在上传时间本身时自动上传的这个问题非常有用。请检查一下

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


});
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2018-01-06
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多