文件上传到本地webapp下
注意事项:引入必要的依赖、form表单的属性、后端接收形式。
前言
写本文的用意在于分享,希望大家多多批评。框架用的是springboot,写的一个小demo,练习 文件上传到本地库。
一、准备工作
1.1、pom文件中还需引入依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
二、上传页面编写
1.编写XXX.jsp
对jsp页面的总结:
1、上传文件输入框类型为type = “file” 记得要命名name=“X”
2、form表单提交方法为method = “post”,
3、enctype=“multipart/form-data”
4、接口以MultipartFile 接收X,这个X就是1中的name。
代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data">
<div align="center">
<span>
<input type="file" name = "file">
</span>
<input type="submit" value="上传" />
</div>
</form>
</body>
</html>
2.编写接口
对接口的总结:
1、MultipartFile file,这里的file对应input中的name=“file”.
2、path为项目的webapp的路径。
3、通过multipartFile 的file.transferTo(File xx);来将上传的文件file存放于xx中。
4、new File(path+“/”+fileName+extName) 是用来创建File对象,并赋予值。其中fileName是新的文件名,extName是扩展名,path是webapp路径。
代码如下:
@Controller
@RequestMapping("/file")
public class uploadLocal {
@RequestMapping("/upload")
@ResponseBody//表示返回的字符串不会作为地址,仅与返回类型同步
public String localUpload(MultipartFile file, HttpServletRequest request) throws Exception {
//获取webapp的路径
String path = request.getSession().getServletContext().getRealPath("/file");
System.out.println("打印path:"+path);
File f = new File(path);
//判断路径若不存在则创建
if(!f.exists()){
f.mkdirs();
}
//获取当前时间用于给新文件命名
Date date = new Date();
//给出时间格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//以此来作为新文件名的一部分
String fileName = simpleDateFormat.format(date);
/*获取原始文件名带扩展名*/
String allName = file.getOriginalFilename();
System.out.println("原始文件名allName:"+allName);
/*获取扩展名 例如.doc */
String extName = allName.substring(allName.lastIndexOf("."));
System.out.println("扩展名extName:"+extName);
//将传过来的file
file.transferTo(new File(path+"/"+fileName+extName));
//返回浏览器upLoadSuccess
return "uploadSuccess";
}
}
三、演示
提示:这里对文章进行总结:
1、未上传前:
2、选择文件
3、点击上传
4、项目路径下上传成功: