springboot实现多文件上传

来源:互联网 发布:python中文注释 编辑:程序博客网 时间:2024/05/01 10:54

关于文件上传,写过两个版本,分别是从两个博客上学来的,这里都展示出来

第一种

@Controller
public class FileUploadController {
@RequestMapping("/files")
public String file() {
return "fileupload";
}
@RequestMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {


BufferedOutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败"+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败"+e.getMessage();
}
return "上传成功";
}else{
return "上传失败";
}
}
}

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>文件上传</title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<p>文件:<input type="file" name="file" /></p>
<p><input type="submit" value="上传" /></p>
</form>
</body>
</html>

第二种

@Controller
public class IndexController {
@Value("${web.upload-path}")
private String uploadPath;

/**
* 上传页面.将显示已存在的文件
* @param model
* @return
*/
@RequestMapping(value="/index",method=RequestMethod.GET)
private String index(Model model){
File[] files=new File(uploadPath).listFiles();
model.addAttribute("files",files);
return "index";
}

@RequestMapping(value="index",method=RequestMethod.POST)
public String index(HttpServletRequest request,@RequestParam("headimg")MultipartFile[] files) throws Exception{
System.out.println("name====="+request.getParameter("name"));
if(files!=null&&files.length>=1){
BufferedOutputStream bw=null;
try{
String fileName=files[0].getOriginalFilename();
//判断是否有文件且是否为图片文件
if(fileName!=null&&!"".equalsIgnoreCase(fileName.trim())&&isImageFile(fileName)){
//创建文件输出对象
File outFile=new File(uploadPath+"/"+UUID.randomUUID().toString()+getFileType(fileName));
//拷贝文件到输出文件
FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile);
}
}catch(Exception e){
throw e;
}finally{
try{
if(bw!=null){
bw.close();
}
}catch(IOException e){
throw e;
}
}
}
return "redirect:/index";
}
/**
* 获得文件后缀名
* @param fileName
* @return
*/
private String getFileType(String fileName) {
if(fileName!=null && fileName.indexOf(".")>=0) {
            return fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        return "";
}
/**
* 判断文件是否为图片文件
* @param fileName
* @return
*/
private boolean isImageFile(String fileName) {
String [] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"};
       if(fileName==null) {return false;}
       fileName = fileName.toLowerCase();
       for(String type : img_type) {
           if(fileName.endsWith(type)) {return true;}
       }
       return false;
}
}

<!DOCTYPE html>
<html lang="zh-CN"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">


    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>文件上传</title>
    </head>
    <body>
        <h2>已有文件:</h2>
        <p th:each="file : ${files}">
            <img th:src="${file.name}" style="height:80px;"/>,文件名称:<span th:text="${file.name}"></span>
        </p>
        <hr/>
        <form method="post" enctype="multipart/form-data">
            昵称:<input name="name" type="text"/>
            <br/>
            头像:<input name="headimg" type="file"/>
            <br/>
            <button type="submit">确定上传</button>
        </form>
    </body>
</html>


spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false


web.upload-path=D:/temp/


spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
  classpath:/static/,classpath:/public/,file:${web.upload-path}

0 0
原创粉丝点击