SSM-13-文件
文件上传
- commons-fileupload-1.3.12
- comons-io-2.5.jar
控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| @Controller public class FileUploadController {
@RequestMapping("/fileUpload") public String handleFormUpload(@RequestParam("name") String name, @RequestParam("uploadfile") List<MultipartFile> uploadfile, HttpServletRequest request) { if(!uploadfile.isEmpty() && uploadfile.size()>0 ) { for (MultipartFile file: uploadfile) { String originalFiename = file.getOriginalFilename(); String dirPath = request.getServletContext().getRealPath("/upload/"); File filePath = new File(dirPath); if(!filePath.exists()) { filePath.mkdir(); } String newFilename = name + "_" + UUID.randomUUID() + "_" + originalFiename; try { System.out.println(dirPath); file.transferTo(new File(dirPath +"/" + newFilename)); System.out.println(dirPath + newFilename); } catch (Exception e) { e.printStackTrace(); return "error"; } } return "success"; }else { return "error"; } } }
|
springmvc-config
1 2 3 4 5 6
| <bean id="multipartResolver" class= "org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> </bean>
|
jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>文件上传</title> <script>
function check(){ var name = document.getElementById("name").value; var file = document.getElementById("file").value; if(name==""){ alert("填写上传人"); return false; } if(file.length==0||file==""){ alert("请选择上传文件"); return false; } return true; } </script> </head> <body> <form action="${pageContext.request.contextPath }/fileUpload" method="post" enctype="multipart/form-data" onsubmit="return check()"> 上传人:<input id="name" type="text" name="name" /><br /> 请选择文件:<input id="file" type="file" name="uploadfile" multiple="multiple" /><br /> <input type="submit" value="上传" /> </form> </body> </html>
|
有个坑点,我上传后就是无法上传到upload文件夹内,只能是文件夹外,处理方法,我在Dirpath和newFilename之间加了一个”/“
文件下载
jsp
1 2 3 4 5 6 7 8 9 10 11
| <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>文件上传</title> <body> <a href="${pageContext.request.contextPath }/download?filename=1.jpg">文件下载</a> </body> </html>
|
控制器
1 2 3 4 5 6 7 8 9 10 11
| @RequestMapping("/download") public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, String filename) throws Exception{ String path = request.getServletContext().getRealPath("/upload/"); File file = new File(path + File.separator + filename); HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", filename); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK); }
|
这样就能下载文件了,这里学到几个点
- File.separator 这个比我写死的”/“好,这里我猜会动态变的,类似于c语言的宏,linux分割跟win分割不一样
- 其余差不多都是套路
中文名下载
这是非常艰难的一次尝试,花了我4个钟解决乱码问题,先上代码
控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @RequestMapping("/download") public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, String filename) throws Exception{ String path = request.getServletContext().getRealPath("/upload/"); byte buf[] = request.getParameter("filename").getBytes("iso8859-1"); String name = new String(buf,"UTF-8"); File file = new File(path+File.separator+name); HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", filename); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers,HttpStatus.OK); }
|
下载部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="java.net.URLEncoder"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>下载页面</title> </head> <body> <%-- <a href="${pageContext.request.contextPath }/download?filename=1.jpg"> 文件下载 </a> --%> <a href="${pageContext.request.contextPath }/download?filename=<%= URLEncoder.encode("壁纸.jpg", "UTF-8")%>"> 中文名称文件下载 </a> </body> </html>
|
经过debug,发觉是jsp到控制器这部分出现了乱码,大概猜测过程如下:
jsp -> tomcat -> controller,由于tomcat默认编码为ISO-8859-1,当jsp将utf-8的参数传入的时候,tomcat将其编一次码,变成iso-8859,所以变成???然后controller拿到的是tomcat编码过后的数据,所以就出现了乱码
解决方法: 将编码过后的数据进行解码,转成utf-8我们就得到了原始数据
然后原始数据需要传回去的话,也就是变成
controller->tomcat->jsp
他会相应的进行一次解码,如果我们直接将参数改成utf-8传回去,就会导致tomcat解码错误,所以我们需要传出去的还是原始数据,我们只需自己获取路径名的时候解析成我们想要的就行,
这些见解只是我在未学习servlet的时候的,将来如果有时间学servlet,我觉得这个肯定会改动,毕竟太粗略,而且没有依据,只是凭空猜测
本文作者:NoOne
本文地址: https://noonegroup.xyz/posts/882ef332/
版权声明:转载请注明出处!