--- layout: post title: 前JS 和 后springmvc操作文件上传 category: 前端 tags: Javascript keywords: description: 记录web页面上传图片的过程,后台是spring及其组件springmvc接收处理,可以实现在chrome和Firefox的文件上传操作。 --- {:toc} ### 准备条件 - [JQuery-2.2.4](https://jquery.com/){:target="_blank"} - [fileapi.js(html5版本)](https://github.com/mailru/FileAPI){:target="_blank"} - springmvc后端环境 ### 操作示例 **前端:** 引入js ```html ``` 添加文件的DOM元素 ```html
``` 操作文件上传的JS代码 ```javascript uploadSuiteLogo("uploadDiv"); /** * 上传文件 * @param {String} id */ function uploadSuiteLogo(id){ $('#'+id).fileapi({ url: '${static_file_path}/console/file/upload', multiple: false, maxSize: 20 * FileAPI.MB, autoUpload: true, onComplete:function(e,data){ var result = data.result; if (result.code == 0) { //在文件上传成功后,处理返回值 $("#uploadDiv").css('background-image','url(' + result.data + ')') $("#suite-logo-path").val(result.data) }else{ alert(result.msg); } } }); } ``` JS操作文件的id是``元素所在div的id。 `static_file_path`为后端自定义的Request的属性。 **后端:** springmvc的配置 ```xml uploadFileError ``` 处理上传的文件 ``` import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; ``` ```java @RequestMapping(value = "/file/upload") @ResponseBody public ResponseBean loginPage(HttpServletRequest request,HttpServletResponse response) { MultipartFile file = ((MultipartHttpServletRequest)request).getFile("filedata"); if(file == null || file.isEmpty()){ return new ResponseBean(CodeEnum.C_21, "文件未获取到"); } System.out.println("Process file: "+file.getOriginalFilename() ); System.out.println("文件长度: " + file.getSize()); System.out.println("文件类型: " + file.getContentType()); System.out.println("文件名称: " + file.getName()); System.out.println("文件原名: " + file.getOriginalFilename()); System.out.println("========================================"); String fileName = UUID.randomUUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); String filePath = MessageFormat.format(ValueConstants.LOGO_PATH_FILE, fileName); System.out.println("保存位置: " + filePath); String pathUrl = ValueConstants.LOGO_PATH_WEB + MessageFormat.format(ValueConstants.LOGO_PATH_DB, fileName); File dest = new File(filePath); dest.mkdirs(); try { file.transferTo(dest); } catch (IllegalStateException | IOException e) { LOG.error("logo上传出错:"+e.getMessage(),e); } return new ResponseBean(CodeEnum.C_0, pathUrl); } ``` 其中`ResponseBean`是自封装的返回格式对象,`getFile("filedata")`中的`filedata`与``为相同值,且``需要在`
`标签内 **经过测试,在chrome和Firefox下正常使用**