Ajax簡單非同步上傳圖片並回顯
前臺程式碼
上傳圖片按鈕
<a href="javascript:void(0)" onclick="uploadPhoto()">選擇圖片</a>
隱藏的檔案選擇器
<input type="file" id="photoFile" style="display: none;" onchange="upload()">
圖片預覽
<img id="preview_photo" src="" width="200px" height="200px">
去除圖片預覽未選擇時預設時的邊框
<style> img[src=""],img:not([src]){ opacity:0; } </style>
JavaScript部分
<script> function uploadPhoto() { $("#photoFile").click(); } /** * 上傳圖片 */ function upload() { if ($("#photoFile").val() == '') { return; } var formData = new FormData(); formData.append('photo', document.getElementById('photoFile').files[0]); $.ajax({ url:"${pageContext.request.contextPath}/system/uploadPhoto", type:"post", data: formData, contentType: false, processData: false, success: function(data) {if (data.type == "success") { $("#preview_photo").attr("src", data.filepath+data.filename); $("#productImg").val(data.filename); } else { alert(data.msg); } }, error:function(data) { alert("上傳失敗") } }); } </script>
後臺程式碼
/** * 圖片上傳 * @param photo * @param request * @return */
@RequestMapping(value="/upFile",method = RequestMethod.POST)
@ResponseBody
public Object upFile(HttpServletRequest request,@RequestParam(value="file",required=false) MultipartFile file) throws Exception{
System.out.println("=====upFile======");
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
Map<String,Object> map = new HashMap<String,Object>();
String ffile = DateUtil.getDays(), fileName = "";
if (null != file && !file.isEmpty()) {
String filePath = PathUtil.getClasspath() + Const.FILEPATHIMG + ffile; //檔案上傳路徑
fileName = FileUpload.fileUp(file, filePath, this.get32UUID()); //執行上傳
map.put("filePath",Const.FILEPATHIMG + ffile + "/" + fileName);
map.put("msg","success");
}else{
map.put("msg","上傳失敗");
}
return map;
}
工具類:FileUpload
public class FileUpload { /**上傳檔案 * @param file //檔案物件 * @param filePath //上傳路徑 * @param fileName //檔名 * @return 檔名 */ public static String fileUp(MultipartFile file, String filePath, String fileName){ String extName = ""; // 副檔名格式: try { if (file.getOriginalFilename().lastIndexOf(".") >= 0){ extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); } copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", ""); } catch (IOException e) { System.out.println(e); } return fileName+extName; } /** * 寫檔案到當前目錄的upload目錄中 * @param in * @param fileName * @throws IOException */ private static String copyFile(InputStream in, String dir, String realName) throws IOException { File file = mkdirsmy(dir,realName); FileUtils.copyInputStreamToFile(in, file); return realName; } /**判斷路徑是否存在,否:建立此路徑 * @param dir 檔案路徑 * @param realName 檔名 * @throws IOException */ public static File mkdirsmy(String dir, String realName) throws IOException{ File file = new File(dir, realName); if (!file.exists()) { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } file.createNewFile(); } return file; } /**下載網路圖片上傳到伺服器上 * @param httpUrl 圖片網路地址 * @param filePath 圖片儲存路徑 * @param myFileName 圖片檔名(null時用網路圖片原名) * @return 返回圖片名稱 */ public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) { URL url; //定義URL物件url BufferedInputStream in; //定義輸入位元組緩衝流物件in FileOutputStream file; //定義檔案輸出流物件file try { String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName; //圖片檔名(null時用網路圖片原名) url = new URL(httpUrl); //初始化url物件 in = new BufferedInputStream(url.openStream()); //初始化in物件,也就是獲得url位元組流 //file = new FileOutputStream(new File(filePath +"\\"+ fileName)); file = new FileOutputStream(mkdirsmy(filePath,fileName)); int t; while ((t = in.read()) != -1) { file.write(t); } file.close(); in.close(); return fileName; } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }