第8章 文件上传

表单上传

1.修改上传限制
SpringBoot默认允许文件上传的限制是2M,通过修改application.yml文件来更改文件上传限制

spring:
    servlet:
    multipart:
      max-file-size: 10MB    #单个文件限制
      max-request-size: 30MB  #单次文件上传限制(多个文件)

2.编写静态网页html或Thymeleaf模板填写表单
在resources/static文件夹下新建fileupload.html文件
表单的提交方式必须是post,enctype="multipart/form-data"

文件描述:
文件:

3.编写处理器程序处理文件上传
在com.neuedu.controller包中新建FileHandler处理器类

@RestController
public class FileHandler {
    
    @PostMapping("/upload")
    public String upload(@RequestParam("mfile")MultipartFile file, String fdes, HttpServletRequest request) throws Exception{
        System.out.println(fdes);
        if(file.isEmpty()) {
            return "no file";
        }
        //获得原始文件名
        String fname = file.getOriginalFilename();
        //获得文件大小
        long size = file.getSize();
        System.out.println(fname+":"+size+"Byte");
        //获得原始扩展名
        String ext_name = fname.substring(fname.lastIndexOf("."));
        //新文件名
        String new_name = System.currentTimeMillis()+ext_name; 
        //保存位置
        String path = request.getRealPath("/images/upload");
        File fp = new File(path);
        if(!fp.exists()) {
            fp.mkdirs();
        }
        //保存文件
        File f = new File(fp, new_name);
        file.transferTo(f);
        System.out.println(f.getPath());
        return request.getContextPath()+"/images/upload/"+f.getName();
    }
}

4.运行

填写表单

运行结果
控制台

Ajax文件上传

在resources/static文件夹中新建js文件夹并引入JQuery文件
在static中新建ajaxFileUpload.html文件
静态网页或模板代码为





Insert title here


    
文件描述:
文件:

后台处理器程序不用修改
点击上传可以看到下方图片出现预览效果,图片已经上传成功


测试效果

你可能感兴趣的:(第8章 文件上传)