1.概述
在最初的http協議中,沒有上傳文件方面的功能。rfc1867(http://www.ietf.org/rfc/rfc1867.txt )為http協議添加了這個功能。瀏覽器按照此規范將用戶指定的文件發送到服務器。服務器再按照此規范,解析出文件。大部分的http server都支持此協議,比如tomcat(本文用的是Spring MVC,即HttpServelet來接收請求)。
網上很多博客,以及插件的做法,是建一個iframe用戶無刷新請求,再建一個form用於提交。但其實可以直接用JavaScript和ajax提交。
2.前端實現
首先,需要type為file的input標簽,該標簽用於選擇文件,手機和PC都適用。
然后,當你點擊file input標簽的時候,會彈出選擇文件控件(該控件是操作系統內部提供的)
最后,就是提交form(form的enctype必須為“multipart/form-data”),提交form的目的是把file input里面的文件提交給服務器。用一個submit按鈕提交form。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"> </head> <body> <form name="myform" enctype="multipart/form-data" action="http://localhost/uploadImage" method=post> <input name="userfile1" type="file" onchange="upload(this);"> </form> </body> <script> function upload() { var myform = document.forms['myform']; myform.method = 'POST'; myform.submit(); } </script> </html>
3.后端實現
@RequestMapping(value = "/uploadImage") @ResponseBody public String uploadImage(HttpServletRequest request) throws IOException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request; Iterator<String> iterator = multipartRequest.getFileNames(); String fileName = ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String dir = "upload/" + sdf.format(new Date()) + "/"; String realPath = request.getSession().getServletContext().getRealPath("/"); while(iterator.hasNext()){ MultipartFile multipartFile = multipartRequest.getFile(iterator.next()); if(multipartFile != null){ String fn = multipartFile.getOriginalFilename(); String suffix = fn.substring(fn.lastIndexOf(".")); fileName = dir + Utils.getRandomStringByLength(6) + suffix; String path = realPath + fileName; path = path.replace("\\", "/"); File f = new File(path); if(!f.mkdirs()){ f.mkdir(); } multipartFile.transferTo(f); } } return fileName; }