SpringBoot文件上传(Ajax)

  • Post author:
  • Post category:其他


1.准备前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>fileup</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
    <input type="file" id="file">
    <input type="button" value="sub" onclick="upload()">
</body>
<script>
    function upload() {
        var file = $("#file")[0].files[0];
        var formData = new FormData();
        formData.append("file",file);

        $.ajax({
            type:'post',
            url:'/upload1',
            processData:false,
            contentType:false,
            data:formData,
            success:function (msg) {
                alert(msg);
            }
        });

    }
</script>
</html>

长这个样子

在这里插入图片描述

2.编写Controller

@RestController
public class HelloController {

    @PostMapping("/upload1")
    public String upload1(MultipartFile file,HttpServletRequest request){

        String realPath = request.getServletContext().getRealPath("/img");
        File file1 = new File(realPath);

        if (!file1.exists()) {
            file1.mkdirs();
        }

        try {
            System.out.println("ok");
            file.transferTo(new File(file1,file.getOriginalFilename()));
            return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/img/"+file.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }
}

返回的路径就是图片的相对路径,可通过浏览器直接访问。



版权声明:本文为qq_36336898原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。