一路繁花似锦绣前程
失败的越多,成功才越有价值

导航

 

一、配置pom.xml

<!-- spring boot web支持 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

 

二、配置application.yml

spring:
  http:
    multipart:
      max-file-size: 500MB
      max-request-size: 500MB

 

三、使用方法

@Controller
public class FileUploadController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFiles(@RequestParam("fileName") MultipartFile[] multipartFile,
            HttpServletRequest httpServletRequest) {
        try {
            // 创建文件在服务器端的存放路径
            String dir = httpServletRequest.getServletContext().getRealPath("/static");
            File fileDir = new File(dir);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            // 生成文件在服务器端存放的名字
            for (int i = 0; i < multipartFile.length; i++) {
                String fileSuffix = multipartFile[i].getOriginalFilename()
                        .substring(multipartFile[i].getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString() + fileSuffix;
                File file = new File(fileDir + "/" + fileName);
                // 上传
                multipartFile[i].transferTo(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }
}
<input type="file" onchange="upload(this)">

<script type="text/javascript">
    function upload(obj){
        var formData=new FormData();
        formData.append("fileName",obj.files[0]);
        $.ajax({
            type:"post",
            url:"http://localhost:8080/upload",
            data:formData,
            success:function(data){
                console.log(data);
            }
        });
    }
</script>

 

 

posted on 2020-03-30 22:23  一路繁花似锦绣前程  阅读(658)  评论(0编辑  收藏  举报