图片上传并回显是一个最基本的功能, 本文只简单实现了一个 demo, 并没有进行复杂的判断, 简单记录下操作流程:
JS 中用到了 Formdata:FormData 对象用以将数据编译成键值对, 以便用 XMLHttpRequest 来发送数据. 其主要用于发送表单数据, 但亦可用于发送带键数据 (keyed data). 如果表单 enctype 属性设为 multipart/form-data , 可以用 new formdata 对象来模拟 submit() 方法来发送数据.
前端代码实现:
- <img width="100" height="100" id="ImgUrl"/>
- <form id="formTag" enctype="multipart/form-data">
- <div class="uploadImgBtn" id="uploadImgBtn">
- <input class="uploadImg" type="file" name="file" id="tpfile">
- </div>
- </form>
CSS 样式:
- <style>
- .uploadImgBtn {
- width: 100px;
- height: 100px;
- cursor: pointer;
- position: relative;
- background: url("img/add.gif") no-repeat;
- -webkit-background-size: cover;
- background-size: cover;
- }
- .uploadImgBtn .uploadImg {
- position: absolute;
- right: 0;
- top: 0;
- width: 100%;
- height: 100%;
- opacity: 0;
- cursor: pointer;
- }
- </style>
Ajax 代码实现:
- <script>
- $(document).ready(function(){
- $("#tpfile").on("change", upload );
- })
- function upload(){
- var self = this;
- $.Ajax({
- url: "/upload/uploadPic.do",
- type: "post",
- dataType: "json",
- cache: false,
- data: new FormData($("#formTag")[0]),
- processData: false,// 不处理数据
- contentType: false, // 不设置内容类型
- success: function(data){
- $("#ImgUrl").attr("src", data.path);
- /*
- 图片显示路径出错, 没解决: 反斜杠转义
- $(self).parent().CSS({
- "background-image": "url("+data.path+")"
- })*/;
- }
- })
- }
- </script>
后台代码实现:
- @RequestMapping("/upload/uploadPic.do")
- public void uploadPic(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
- try {
- // 获取图片原始文件名
- String originalFilename = file.getOriginalFilename();
- // 文件名使用当前时间
- String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
- // 图片上传的相对路径(因为相对路径放到页面上就可以显示图片)
- String path = File.separator+"img"+File.separator + name + "_" +originalFilename ;
- System.out.println(path);
- // 图片上传的绝对路径
- String url = request.getSession().getServletContext().getRealPath("") + path;
- File dir = new File(url);
- if(!dir.exists()) {
- dir.mkdirs();
- }
- // 上传图片
- file.transferTo(new File(url));
- // 将相对路径写回(JSON 格式)
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("path",path);
- // 设置响应数据的类型 JSON
- response.setContentType("application/json; charset=utf-8");
- response.getWriter().write(jsonObject.toString());
- } catch (Exception e) {
- //throw new RuntimeException("服务器繁忙, 上传图片失败");
- throw new RuntimeException(e);
- }
- }
测试结果:
虽然简单实现了, 但 JSON 格式转义出错, 还没有解决.
========================= 华丽的分割线 ===========================
实现多文件同时上传
文件上传有很多的注意细节:
1, 为保证服务器安全, 上传文件应该放在外界无法直接访问的目录下, 比如放于 Web-INF 目录下.
2, 为防止文件覆盖的现象发生, 要为上传文件产生一个唯一的文件名.
3, 为防止一个目录下面出现太多文件, 要使用 hash 算法打散存储.
4, 要限制上传文件的最大值.
5, 要限制上传文件的类型, 在收到上传文件名时, 判断后缀名是否合法.
前端实现:
springmvc 多文件上传
- <form action="/upload/uploadMulFile.do" enctype="multipart/form-data" method="post">
- 上传文件 1:<input type="file" name="files"><br/>
- 上传文件 2:<input type="file" name="files"><br/>
- <input type="submit" value="提交"/>
- </form>
后端代码实现:
- /**
- * 多文件上传
- * @param request
- */
- @RequestMapping("/upload/uploadMulFile.do")
- public String uploadMulFile(@RequestParam("files") MultipartFile []multipartFiles, HttpServletRequest request){
- String path = File.separator+"upload"+File.separator ;
- String realPath = request.getSession().getServletContext().getRealPath("") + path;
- File dir = new File(realPath);
- if(!dir.exists()) {
- dir.mkdirs();
- }
- if(multipartFiles == null || multipartFiles.length == 0){
- return null;
- }
- if(multipartFiles.length>0){
- for (MultipartFile file :multipartFiles){
- try {
- file.transferTo(new File(realPath + file.getOriginalFilename()));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
- return "tp";
- }
上传下载文件详细参考博客 3.
参考:
- https://www.cnblogs.com/kongxc/p/7831837.html
- https://www.jianshu.com/p/18206a94fee5
- https://www.cnblogs.com/xdp-gacl/p/4200090.html
来源: https://yq.aliyun.com/articles/680002