標籤:try spring tip pat byte 處理 blog ring exce
本程式碼片段用於spring boot+hibernate,用maven構建
一:
ajaxFileUpload為了實現無重新整理非同步提交檔案,構建 iframe 然後建立form表單 再將要上傳的檔案寫上去再提交.但是原代碼 卻沒有處理data.所以這塊內容需要我們自己加上去.下面紅色部分為修改ajaxFileUpload.js的三處地方:(對比源碼修改)1.createUploadForm: function(id, fileElementId,data);2.if (data) { for (var i in data) { $(‘<input type="hidden" name="‘ + i + ‘" value="‘ + data[i] + ‘" />‘).appendTo(form); } }3.var form = jQuery.createUploadForm(id, s.fileElementId,s.data);
html部分:
<form id="form1" runat="server" method="post" enctype="multipart/form-data">
<div>
<div class="_box">選擇圖片</div>
</div>
<div class="none">
<input type="file" name="fileID" id="fileID" />
</div>
</form>
二:
$.ajaxFileUpload({
url: ‘URL‘, type: ‘post‘, data : { url : url }, secureuri: false, //一般設定為false fileElementId: ‘fileID‘, // 上傳檔案的id、name屬性名稱 dataType: ‘JSON‘, //傳回值類型,一般設定為json、application/json 這裡要用大寫 不然會取不到返回的資料 success: function(data, status){ alert(data); }, error: function(data, status, e){ alert(e); } });
三:後台讀取並儲存到檔案夾中 //儲存目錄為 E:\saveIMG
@ResponseBody
@RequestMapping("/addandupload")
public String addandupload(@RequestParam(value="uploadIMG", required=false) MultipartFile file) {
String filename = file.getOriginalFilename();
String filepath = "E:\\saveIMG\\"; //檔案上傳儲存目錄
if (!file.isEmpty()) { //判斷是否有檔案上傳
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filepath, filename)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
頁面顯示多個伺服器圖片:
一:
HTML頁面的IMG標籤中的src用
<img class="example-image" src="*{‘http://127.0.0.1:8080/foodmain/findimg?name=‘+food.foodimg}" alt="${food.foodname}" />
後端http://127.0.0.1:8080/foodmain/findimg?name?方法
@ResponseBody
@RequestMapping("/findimg")
public void findimg(HttpServletResponse response,String name) throws IOException{
File filePic = new File("E:\\saveIMG\\"+name);
if(filePic.exists()){
FileInputStream is = new FileInputStream(filePic);
int i = is.available(); // 得到檔案大小
byte data[] = new byte[i];
is.read(data); // 讀資料
is.close();
response.setContentType("image/*"); // 設定返回的檔案類型
OutputStream toClient = response.getOutputStream(); // 得到向用戶端輸出位元據的對象
toClient.write(data); // 輸出資料
toClient.close();
}
}
JS驗證上傳檔案大小,參考:http://zhuchengzzcc.iteye.com/blog/1573360
ajaxFileUpload上傳帶參數檔案及JS驗證檔案大小