Bootstrap Fileinput 4.4.7檔案上傳例項
阿新 • • 發佈:2019-01-27
本例項所做功能為傳送帶附件郵件,可以上傳多個附件,操作為選擇一個附件以後自動上傳,然後繼續選擇附件,填寫完表單其他資訊,點選儲存傳送帶附件郵件。
HTML標籤
<input id="fileUpload" type="file" name="file" data-show-preview="true" multiple/>
js初始化,設定全域性檔名引數
var fileName = [];
function initFileInput(id, url) {
$("#" + id).fileinput({
language: 'zh',
uploadAsync:false ,
uploadUrl:url,
browseClass: "btn btn-secondary",
textEncoding:"UTF-8",
showUpload: false,
showPreview :true,
dropZoneEnabled: false,
maxFileCount:5,
fileActionSettings:{
showUpload: true
},
enctype:'multipart/form-data',
msgFilesTooMany: "選擇上傳的檔案數量({n}) 超過允許的最大數值{m}!",
}).on("filebatchselected", function(event, files) {
$("#fileUpload").fileinput("upload");
}).on("filebatchuploadsuccess", function (event, data, previewId, index) {
if(data.response.success == true)
{
fileName.push(data.response.fileName);
}else{
alert("上傳失敗!");
}
$("#fileUpload").fileinput("clear");
$("#fileUpload").fileinput("reset");
}).on('fileerror', function(event, data, msg) {
alert(msg);
});
}
java後臺上傳檔案程式碼
@RequestMapping(value="/fileupload")
@ResponseBody
public Map<String, Object> fileUpload(HttpServletRequest request, HttpServletResponse response) {
ResourceBundle bundle = PropertyResourceBundle.getBundle("application");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
Map<String,MultipartFile> fileMap = multipartRequest.getFileMap();
String rootPath = bundle.getString("upLoadUrl");
String filePath = rootPath;
Map<String, Object> map = new HashMap<>();
map = uploadFiles(filePath,fileMap);
return map;
}
實際上傳操作,返回上傳操作經過處理的檔名,保證伺服器端檔名唯一
public Map<String, Object> uploadFiles(String savePath,Map<String,MultipartFile> fiLeMap){
Map<String, Object> map = new HashMap<>();
try {
String fileName = "";
if(fiLeMap!=null){
for(Map.Entry<String, MultipartFile> entity:fiLeMap.entrySet()){
MultipartFile f = entity.getValue();
if(f != null && !f.isEmpty()){
String uuid = UUID.randomUUID().toString();
fileName = uuid + "#" + f.getOriginalFilename();
File newFile = new File(savePath + "/" + fileName);
f.transferTo(newFile);
}
}
}
map.put("success", true);
map.put("fileName", fileName);
return map;
}catch (Exception e) {
map.put("success", false);
return map;
}
}
ajax提交其他表單引數和所傳附件檔名集合
$.ajax({
type: "POST",
url: 所需要請求地址,
dataType: "json",
traditional:true,
data: {
service:$("#service").select2('val').replace("All",""),
startTime:$("#start").val(),
endTime:$("#end").val(),
reason:$("#reason").val(),
fileName:JSON.stringify(fileName),
outterEmail:isOutterEmail,
innerEmail:isInnerEmail,
isSendEmail:isSendEmail,
subService:$("#subService").select2('val'),
runningStatus:$("#runningStatus").select2('val')
},
success: function(data){
$("#loadingModal").modal("hide");
fileName.splice(0,fileName.length);
alert(data.msg);
if(data.success) {
location.href = "revision";
}
},
error:function(xhr) {
$("#loadingModal").modal("hide");
alert("儲存失敗");
}
});
有問題可以留言