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

我们有一个银行项目,要求在上传文件时必须在其中上传文件本身(意味着自动上传),如何使用Ajax调用来使用Spring Boot自动上传,


这是我拥有的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>


HUH函数
浏览 145回答 1
1回答

繁花不似锦

这是我找到的,并且可以解决此问题的问题,我发现这对于在更新时间本身时自动上传的问题非常有用。请检查一下$('#certificate_document_other').on("change",function(){&nbsp;var objFormData=new FormData();// to capture all form form information inform of object&nbsp;var objFile= $(this)[0].files[0];&nbsp;objFormData.append('file',objFile);&nbsp;$.ajax({&nbsp; &nbsp;url:"/SomeProjetName/fileUpload",&nbsp; &nbsp;type: "POST",&nbsp; &nbsp;enctype:"multipart/form-data",&nbsp; &nbsp;data:objFormData,&nbsp; &nbsp;contentType:false,&nbsp; &nbsp;processType:false,&nbsp; &nbsp;success: function(data){&nbsp; &nbsp; &nbsp; alert('upload SuccessFull');},error:function(xhr,status,errorType){&nbsp; &nbsp; alert(xhr.status);&nbsp; &nbsp; alert(xhr.responseText);}});});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java