配置pom.xml文件
<!-- 文件上传 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
配置springmvc.xml文件
<!-- 文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上传文件大小限制10M --> <property name="maxUploadSize"> <value>10485760</value> </property> <!-- 请求的编码格式, 和 jsp 页面一致 --> <property name="defaultEncoding"> <value>UTF-8</value> </property> </bean>
controller层
@RequestMapping("/uploadFile") @ResponseBody public String uploadFile(@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletRequest req) { System.out.println("springmvc文件上传。。。。"); //获取原始文件名称 String originalFileName = uploadFile.getOriginalFilename(); System.out.println(originalFileName); //存储文件的文件夹名称 String upload = req.getServletContext().getRealPath("upload"); System.out.println(upload); //目的仓库在项目之外 //String upload = "D:\\upload"; //与目的地建立连接 File file = new File(upload); if (!file.exists()) { file.mkdirs(); } //获取文件后缀 String suffix = originalFileName.substring(originalFileName.lastIndexOf(".", originalFileName.length())); String filename = upload.concat(File.separator).concat(UUID.randomUUID().toString()).concat(suffix); System.out.println(filename); try { uploadFile.transferTo(new File(filename)); return originalFileName; } catch (IOException e) { e.printStackTrace(); } return null; } /* * 文件下载 * */ @RequestMapping("/download") public ResponseEntity<byte[]> download(HttpServletRequest req, String filename) { //文件地址在项目内部的(目的地址信息) String upload = req.getServletContext().getRealPath("upload"); //目的仓库在项目之外 //String upload = "D:\\upload" //先拼接具体的位置路径,然后通过file进行建立连接 File file = new File(upload + File.separator + filename); if (!file.exists()) {//如果不存在文件,直接返回null return null; } try { //创建标头文件对象 HttpHeaders headers = new HttpHeaders(); ; //解决乱码问题 String downloadfile = new String(filename.getBytes(StandardCharsets.UTF_8), "iso-8859-1"); //以下载的方式打开文件 headers.setContentDispositionFormData("attachment", filename); //二进制流 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); } catch (Exception e) { e.printStackTrace(); } return null; }
页面html ajax提交二种方式 form
上传文件 <form action="/uplaod/uploading" method="post" enctype="multipart/form-data"> 文件: <input type="file" name="uploadFile"> <input type="submit" value="提交"> </form>
<!--文件上传--> $('#btn').click(function () { var formdata = new FormData(); formdata.append('uploadFile', $('#uploadFile')[0].files[0]); $.ajax({ url: '/uploadFile', type: 'post', contentType: false, processData: false, data: formdata, success: function (data) { console.log(data) document.getElementById("uuFile").value = data; } }) });
<div class="layui-form-item"> <label class="layui-form-label">文件名称:</label> <div class="layui-input-inline layui-col-md4"> <input type="file" name="filenames" id="uploadFile" required lay-verify="required" placeholder="文件名称" autocomplete="off" class="layui-input"> <input type="text" name="filename" id="uuFile" required lay-verify="required" placeholder="文件名称" autocomplete="off" class="layui-input"> </div> <button type="button" class="layui-btn" id="btn">浏览文件</button> </div>
<!--下载--> if (obj.event === 'detail') { alert(11); $.ajax({ type: "POST", url: "/download", data: {filename: data.filename}, dataType: "json", success: function (da) { console.log(da) } });