js爲:
<script type="text/javascript" src="${APP_PATH}/static/bootstrap-fileinput/fileinput.min.js"></script>
<script type="text/javascript" src="${APP_PATH}/static/bootstrap-fileinput/locales/zh.js"></script>
<link href="${APP_PATH}/static/bootstrap-fileinput/fileinput.min.css" rel="stylesheet" />
html:
<form action="news/addnews.action" method="POST" id="addnew_form">
<input type="text" name="head" >
<input type="file" name="newpic" class="myfile"/>
<input type="text" name="body">
<button type="submit" >推送</button>
</form>
js寫法:
$(".myfile").fileinput({
uploadUrl:"${APP_PATH}/news/uploadFile", //接受請求地址
uploadAsync : true, //默認異步上傳
showUpload : false, //是否顯示上傳按鈕,跟隨文本框的那個
showRemove : false, //顯示移除按鈕,跟隨文本框的那個
showCaption : true,//是否顯示標題,就是那個文本框
showPreview : true, //是否顯示預覽,不寫默認爲true
dropZoneEnabled : false,//是否顯示拖拽區域,默認不寫爲true,但是會佔用很大區域
//minImageWidth: 50, //圖片的最小寬度
//minImageHeight: 50,//圖片的最小高度
//maxImageWidth: 1000,//圖片的最大寬度
//maxImageHeight: 1000,//圖片的最大高度
//maxFileSize: 0,//單位爲kb,如果爲0表示不限制文件大小
//minFileCount: 0,
maxFileCount : 1, //表示允許同時上傳的最大文件個數
enctype : 'multipart/form-data',
validateInitialCount : true,
previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
msgFilesTooMany : "選擇上傳的文件數量({n}) 超過允許的最大數值{m}!",
allowedFileTypes : [ 'image' ],//配置允許文件上傳的類型
allowedPreviewTypes : [ 'image' ],//配置所有的被預覽文件類型
allowedPreviewMimeTypes : [ 'jpg', 'png', 'gif' ],//控制被預覽的所有mime類型
language : 'zh'
})
//異步上傳返回結果處理
$('.myfile').on('fileerror', function(event, data, msg) {
console.log("fileerror");
console.log(data);
});
//異步上傳返回結果處理
$(".myfile").on("fileuploaded", function(event, data, previewId, index) {
console.log("fileuploaded");
var ref = $(this).attr("data-ref");
$("input[name='" + ref + "']").val(data.response.url);
});
//上傳前
$('.myfile').on('filepreupload', function(event, data, previewId, index) {
console.log("filepreupload");
});
@RequestMapping("news/uploadFile")
public String uploadFile(MultipartFile newpic)
throws IllegalStateException, IOException {
// 原始圖片名稱
String oldFileName = newpic.getOriginalFilename(); // 獲取上傳文件的原名
// 存儲路徑
String saveFilePath = "D://新建文件夾 (4)//house//src//main//webapp//housepic";
// 新的圖片名稱
String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
// 新圖片
File newFile = new File(saveFilePath + "\\" + newFileName);
// 將內存中的數據寫入磁盤
newpic.transferTo(newFile);
// 將路徑名存入全局變量mynewpic
mynewpic = "./housepic/"+newFileName;
}