文件上傳與文件顯示
1、圖片預覽
前端頁面的代碼如下:
<form action="" enctype="multipart/form-data" method="post"> <input type="file" name="file" id="file" onchange="previewFile(this);"/> <input type="text" id="text"/> <input type="button" value="上傳" id="upload" onclick="uploadImage();"> <img id="image" name = "img" src="" alt="頭像" class="image"> </form>
js代碼:讀取文件
文件一旦開始讀取,無論成功或失敗,實例的 result 屬性都會被填充。如果讀取失敗,則 result 的值為 null ,否則即是讀取的結果,絕大多數的程序都會在成功讀取文件的時候,抓取這個值。
1 /**圖片預覽*/ 2 function previewFile(file){ 3 if(window.FileReader){ 4 var reader = new FileReader(); 5 }else{ 6 alert("瀏覽器不支持") 7 } 8 /**onload事件:文件讀取成功觸發*/ 9 reader.onload = function (e) { 10 document.getElementById('image').src = e.target.result; 11 image = e.target.result; 12 // console.log(image); 13 }; 14 /** 15 * readAsDataURL(): 16 * 該方法將文件讀取為一段以 data: 開頭的字符串, 17 * 這段字符串的實質就是 Data URL,Data URL是一種將小文件直接嵌入文檔的方案。 18 */ 19 reader.readAsDataURL(file.files[0]); 20 21 }
2、文件發送后台
js代碼:發送數據到后台
1 /**提交請求到后台,將文件對象作為json字符串發送*/ 2 var image=''; 3 function uploadImage() { 4 var data = {value:image}; 5 alert(image); 6 $.ajax({ 7 type:'POST', 8 url:'/login/ModifyImage', 9 contentType:'application/json;charset=utf-8', 10 data:JSON.stringify(data),//json字符串格式發送 11 dataType:'json', 12 success:function (result) { 13 readImg(result); 14 alert("成功"); 15 } 16 }); 17 }
3、java后台接收數據
思路:前台傳以data:image/jpeg;base64,開頭的base64編碼的String字符串,后台接收字符串以后先進行base64解碼 .decodeBuffer(),轉換成二進制編碼,然后使用字節輸出流FileOutputStream()將文件保存到指定目錄下。
/**實現上傳圖片功能*/ @RequestMapping(value = "/ModifyImage",method = RequestMethod.POST) @ResponseBody public String changeImage(@RequestBody String data) throws IOException { /**將json字符串轉成json對象*/ JSONObject jsonObject = JSONObject.fromObject(data); /**獲取文件的頭部分*/ String header = "data:image/jepg;base64,"; /**獲取文件的實體部分*/ String image = jsonObject.getString("value"); System.out.println(image.length()); /**剪切頭部分*/ image = image.substring(header.length()); BASE64Decoder decoder = new BASE64Decoder(); /**用base64解碼,decodeBuffer()轉成二進制編碼*/ byte[] bytes = decoder.decodeBuffer(image); long time = System.currentTimeMillis(); /**指定保存的路徑*/ String str = LoginController.class.getPackage().toString(); System.out.println(str); File path = new File("F:/temp/"+time+".jpg"); System.out.println(path); FileOutputStream outputStream = new FileOutputStream(path); outputStream.write(bytes); outputStream.close(); return path.getAbsolutePath(); }
4、后台處理請求
1 /**服務器向瀏覽器發送圖片*/ 2 @RequestMapping(value = "/getImage",method = RequestMethod.POST) 3 @ResponseBody 4 public String sendImg(@RequestBody String path) throws IOException { 5 JSONObject jsonObject = JSONObject.fromObject(path); 6 /**獲取文件的路徑*/ 7 String paths = jsonObject.get("value").toString(); 8 File file = new File(paths); 9 /**讀取圖片*/ 10 BufferedImage image = ImageIO.read(file); 11 ByteArrayOutputStream out = new ByteArrayOutputStream(); 12 ImageIO.write(image,"jpg",out); 13 /**將當前輸出流轉為字節數組*/ 14 byte[] data = out.toByteArray(); 15 BASE64Encoder encoder = new BASE64Encoder(); 16 /**對字節數組進行編碼*/ 17 String imageString = encoder.encodeBuffer(data).trim(); 18 imageString.replaceAll("\n","").replaceAll("\r",""); 19 return imageString; 20 }
5、前端頁面顯示圖片
$("#myImg").attr("src","data:image/jpg;base64,"+res);
注意:data:image/jpg;base64,為Base64編碼的頭
1 /**接收服務器發送過來的圖片*/ 2 function readImg(result) { 3 var data = {value:result}; 4 $.ajax({ 5 type:'POST', 6 url:'/login/getImage', 7 contentType:'application/json;charset=utf-8', 8 data:JSON.stringify(data),//json字符串格式發送 9 dataType:'text', 10 success:function (res) { 11 alert(res); 12 $("#myImg").attr("src","data:image/jpg;base64,"+res);13 } 14 });
