html代碼:
------------------添加--------------------------
accept="image/gif,image/jpeg,image/jpg,image/png"
使用這個可以讓用戶只能看到並上傳圖片
原本是這個accept="image/*"的,后來發現在Chrome瀏覽器上響應過慢,所以加上mime類型,避免全部匹配引起時的瀏覽器響應過慢問題
<input type="file" id="file" style="display:none;" onchange="filechange(event)">//修改,這里如果不用onchange,會出現一個小bug,當你提交后,圖片只能變一次 <img src="" width="200px" height="200px" id="img-change"> <button id="btn">保存圖片</button>
js代碼:
//實現點擊圖片同時,觸發type=file這個input
$("#img-change").click(function () { $("#file").click(); })
當input發生改變時,如果有圖片,則預覽圖片(這里只判斷文件的改變,沒判斷圖片)
/*$("#file").change(function (event) {*/
var filechange=function(event){ var files = event.target.files, file; if (files && files.length > 0) { // 獲取目前上傳的文件 file = files[0];// 文件大小校驗的動作 if(file.size > 1024 * 1024 * 2) { alert('圖片大小不能超過 2MB!'); return false; } // 獲取 window 的 URL 工具 var URL = window.URL || window.webkitURL; // 通過 file 生成目標 url var imgURL = URL.createObjectURL(file); //用attr將img的src屬性改成獲得的url $("#img-change").attr("src",imgURL); // 使用下面這句可以在內存中釋放對此 url 的伺服,跑了之后那個 URL 就無效了 // URL.revokeObjectURL(imgURL); } };
接下來實現當點擊按鈕時,通過jquey的一個插件ajaxupload來進行上傳圖片,
代碼如下:
$("#btn").click(function () { $.ajaxFileUpload({ url: '/imgUpload', fileElementId:'file', dataType:'txt', secureuri : false, success: function (data){ if(data=="yes"){ $("#img-alert").css("display","block"); } }, error:function(data,status,e){ alert(e); } }); });
接下來是后台代碼,我的后台是spring mvc框架,我沒試過不用spring mvc的框架,但最多在攔截時不同,得到后,在文件處理那塊是一樣的
@RequestMapping(value = "/imgUpload") @ResponseBody public synchronized String imgUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws IOException { String tishi="no"; System.out.println("arrive here"); if(!file.isEmpty()) { //System.out.println(file.getOriginalFilename()); String message = System.currentTimeMillis() + file.getOriginalFilename();//現在的文件名是時間戳加原文件名,出現圖片相同時,讀取不出來的bug String realPath = request.getSession().getServletContext().getRealPath("/upload/");//將文件保存在當前工程下的一個upload文件 FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, message));//將文件的輸入流輸出到一個新的文件 message="upload/"+message; HttpSession session=request.getSession(); Integer id=(Integer)session.getAttribute("userid");//在session中獲得用戶id User user=userService.get(id);//在dao層保存數據,也就是圖片的地址 user.setPhoto(message); userService.update(user); tishi="yes";//返回yes,表示存儲成功,可以使用try,catch來捕捉錯誤,這里偷懶不用 } return tishi; }
還有一點,還需再spring mvc框架下配置文件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8" /> <property name="maxUploadSize" value="1048576000" /> <property name="maxInMemorySize" value="40960000" /> </bean>