11.文件上传

templates/index.ftl




    
    
    
    index


${name}

文件上传

页面使用thymeleaf
templates/upload.html:




    upload


    

文件上传

templates/upload2.html:




    upload


    

文件批量上传

文件大小限制:

spring.http.multipart.max-request-size=10KB
spring.http.multipart.max-file-size=10KB

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

@Controller
public class Index2Controller {
    @RequestMapping("/upload")
    public String upload(){
        return "upload";
    }
    @PostMapping("fileUpload")
    public String fileUpload(MultipartFile file, HttpServletRequest request){
        try {
            //获取真实路径
            String dir = request.getServletContext().getRealPath("/files");
            File fileDir = new File(dir);
            if (!fileDir.exists())
                fileDir.mkdirs();
            //原始文件名的前缀
            String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + fileSuffix;
            File files = new File(fileDir + "/" + fileName);
            //上传
            file.transferTo(files);
        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println(e.toString());
            request.getSession().setAttribute("msg","上传失败");
            return "redirect:/upload";
        }
        request.getSession().setAttribute("msg","上传成功");
        return "redirect:/upload";
    }

    @RequestMapping("/upload2")
    public String upload2(){
        return "upload2";
    }
    @PostMapping("fileUpload2")
    public String fileUpload2(MultipartFile[] files, HttpServletRequest request){
        try {
            //获取真实路径
            String dir = request.getServletContext().getRealPath("/files");
            File fileDir = new File(dir);
            if (!fileDir.exists())
                fileDir.mkdirs();
            for (MultipartFile file : files) {
                //原始文件名的前缀
                String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString() + fileSuffix;
                System.out.println(fileName);
                File f = new File(fileDir + "/" + fileName);
                //上传
                file.transferTo(f);
            }
        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println(e.toString());
            request.getSession().setAttribute("msg","上传失败");
            return "redirect:/upload2";
        }
        request.getSession().setAttribute("msg","上传成功");
        return "redirect:/upload2";
    }
}

转载于:https://www.cnblogs.com/fly-book/p/11619038.html

你可能感兴趣的:(java,ui)