標籤:
需要外掛程式:ajaxfileupload.js commons-fileupload-1.3.1.jar
web端:
<form id="saveForm" method="post" enctype="multipart/form-data"><label>廣告圖片:</label><input type="file" id="image1" name="image1" data-options="required:true" /> <img src="../../imgSrc/aaaaaa.jpg" id="img" width="100px",height="100px"/> <input type="button" id="sub" value="上傳"/></form>
<script type="text/javascript">$(function(){ $("#sub").click(function(){ $.ajaxFileUpload({ url:‘upload.do‘, secureuri:false, fileElementId:‘image1‘,//file標籤的id dataType: ‘json‘,//返回資料的類型 success: function (data) { $("#img").attr("src","../../imgSrc/"+data); }, }); });});</script>
java後台:
@RequestMapping("upload") @ResponseBody public String upload(@RequestParam("image1") MultipartFile file,HttpServletRequest req){// String saveFilePath = req.getServletContext().getRealPath("/WEB-INF/upload"); String saveFilePath=Constant.savePath; try { if (!file.isEmpty()) { // 擷取圖片的檔案名稱 String fileName = file.getOriginalFilename(); // 擷取圖片的副檔名 String extensionName = fileName .substring(fileName.lastIndexOf(".") + 1); // 新的圖片檔案名稱 = 擷取時間戳記+"."圖片副檔名 String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName; ImgUtils.saveFile(newFileName, file, saveFilePath); return newFileName; }else{ return "exception"; } } catch (Exception e) { e.printStackTrace(); return "Exception"; } }
public static void saveFile(String newFileName, MultipartFile filedata,String saveFilePath) { // TODO Auto-generated method stub // 根據設定檔擷取伺服器圖片存放路徑 /* 構建檔案目錄 */ File fileDir = new File(saveFilePath); if (!fileDir.exists()) { fileDir.mkdirs(); } try { FileOutputStream out = new FileOutputStream(saveFilePath + "\\" + newFileName); // 寫入檔案 out.write(filedata.getBytes()); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
tomcat:
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true"> <Context docBase="D:\upload" path="/imgSrc"/>
web端 圖片上傳