1、讲解springboot文件上传 MultipartFile file,源自SpringMVC
注意点:
如果想要直接访问html页面,则需要把html放在springboot默认加载的文件夹下面
MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)
直接上html代码
<!DOCTYPE html>
<html>
<head>
<title>uploadimg.html</title>
<meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="/js/test.js" type="text/javascript"></script>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
文件:<input type="file" name="head_img"/>
姓名:<input type="text" name="name"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
下面是controller代码,只是demo,实际开发逻辑代码写在server实现层
package com.study.studyBoot.controller;
import com.study.studyBoot.model.JsonData;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@RestController
public class FileController {
//final Logger logger = logger.getLogger(FileController.class);
private static final String filePath = "D:/IDEA/studyBoot/src/main/resources/static/images/";
/**
* @Description: 上传图片接口
* @author: panboyang
* @date :2019-06-26 17:55:17
* @params: head_img表单提交名称 ,filePath路径自定义
*/
@RequestMapping(value = "upload")
@ResponseBody
public JsonData upload(@RequestParam("head_img") MultipartFile multipartFile, HttpServletRequest request) {
//multipartFile.getSize(); 根据自己的个人情况来定义限制上传大少
JsonData data = new JsonData();
if (multipartFile.isEmpty()) {
return new JsonData(-1, "文件不能为空");
} else {//获取用户名
String name = request.getParameter("name");
System.out.println("用户名:" + name);
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
System.out.println("上传的文件名为:" + fileName);
// 获取文件的后缀名,比如图片的jpeg,png
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传的后缀名为:" + suffixName);
// 文件上传后的路径
fileName = UUID.randomUUID() + suffixName;
System.out.println("转换后的名称:" + fileName);
File dest = new File(filePath + fileName);
//dest.getPath() 返回文件路径
try {
multipartFile.transferTo(dest);
return new JsonData(1,dest.getPath(),"sues to save");
}catch (IllegalStateException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return new JsonData(-1,null,"fail to save");
}
}
}