文件上传
文件上传三要素
不管是 ssm还是spring boot表单项都要修改
1:表单项type=file;
2:表单提交方式post;
3:表单的enctype属性是多部分表单形式:enctype=“multipart/form-data” 当enctype修改后request.getParameter()将会失效,提交方式将不是键值对
ssm框架使用
- 导入架包fileupload
- 在Spring-mvc配置文字上传解析器
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上传总文件大小-->
<property name="maxUploadSize" value="5242800" />
<!--上传单个文件大小-->
<property name="maxUploadSizePerFile" value="5242800" />
<!--上传文件的编码类型-->
<property name="defaultEncoding" value="UTF-8" />
</bean>
3.controller层
@RequestMapping("admin_add_User")
@ResponseBody
public void admin_add_User(MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws IOException {
//如果文件不为空,写入上传路径
String filename=null;
if(!file.isEmpty()){
//获取路径
String path=request.getServletContext().getRealPath("/");
//保存文件名
filename = file.getOriginalFilename();
//保存文件
file.transferTo(new File(path+"\\img\\"+filename));
//拼接存入数据库的名称
filename="img/"+file.getOriginalFilename();
}
springboot使用
1.页面
<form action="/ops/user/add" method="post" enctype="multipart/form-data" class="layui-form">
<input type="file" name="file">
</form>
2.controller
@RequestMapping("/add")
public String addUser(MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();//获取文件名
fileName = getFileName(fileName); //添加时间戳后的文件名
String filepath = getUploadPath(); //获取当前系统路径
if (!file.isEmpty()) { //如果文件不为空
//上传
try (BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(filepath + File.separator + fileName)))) {
out.write(file.getBytes());
out.flush();
} catch (FileNotFoundException e) {
System.out.println("上传文件失败 FileNotFoundException:" + e.getMessage());
} catch (IOException e) {
System.out.println("上传文件失败 IOException:" + e.getMessage());
}
fileName="uplode/"+fileName; //拼接存入数据库的路径
} else {
System.out.println("上传文件失败,文件为空");
}
return "close";
}
工具方法
/**
* 文件名后缀前添加一个时间戳
*/
private String getFileName(String fileName) {
int index = fileName.lastIndexOf(".");
final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");
String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
return fileName;
}
/**
* 获取当前系统路径
*/
private String getUploadPath() {
File path = null;
try {
path = new File(ResourceUtils.getURL("classpath:").getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (!path.exists()) path = new File("");
File upload = new File(path.getAbsolutePath(), "static/upload/");
if (!upload.exists()) upload.mkdirs();
return upload.getAbsolutePath();
}