1.首先為html代碼以及js代碼
<div id="uploadDiv" style="display:none;"> <!-- The fileinput-button span is used to style the file input field as button --> <span class="btn btn-success fileinput-button"> <i class="glyphicon glyphicon-plus"></i> <span>文件選擇</span> <!-- The file input field used as target for the file upload widget --> <input id="fileupload" type="file" name="file" > </span> <button id="uploadBtn" class="btn btn-primary disabled" >確認上傳</button> <br> <!-- The global progress bar --> <div id="progress" class="progress"> <div class="progress-bar progress-bar-success"></div> </div> <!-- The container for the uploaded files --> <div id="msgDiv" class="files"></div> </div>
$("#uploadBtn").click(function(){
var dialog = $("#uploadDiv").clone().dialog({
title: "附件上傳",
width : '75%',
height : 500,
modal : true
});
$('#fileupload', dialog).fileupload({
dataType: 'json',
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar', dialog).css(
'width',
progress + '%'
).html(progress + '%');
$("#msgDiv", dialog).html("處理中……");
},
add: function (e, data) {
data.url = "ra/suspiciousCase/uploadTotal";
data.submit();
$("#uploadBtn", dialog).off('click').on('click', function () {
var id = getUrlParam('id');
data.url = "ra/suspiciousCase/upload?id="+id;
data.submit();
setTimeout(function(){handleUploadTable();}, 3000);//延遲執行刷新
});
},
done: function (e, data) {
var isTotal = data.url.indexOf("uploadTotal") > -1;
var tip = isTotal ? "解析成功,請點擊“確認上傳”" : "上傳";
var result = data.result;
var msg = "<b>" + tip + "</b>"
var bar = $('#progress .progress-bar');
bar.removeClass("progress-bar-warning progress-bar-success");
if(!result.success){
msg = "<b>" + tip + "失敗:</b>"+result.error;
bar.addClass("progress-bar-warning");
$("#uploadBtn", dialog).addClass("disabled");
}else{
bar.addClass("progress-bar-success");
msg = "<b>" + tip + "成功:</b>";
if(isTotal){
$("#uploadBtn", dialog).removeClass("disabled");
}
}
if(result.totalInfo){
msg += "<br>";
msg += "<b>提示信息:</b>" + result.totalInfo;
}
msg += "<br><b>文件名稱:</b>" + data.files[0].name;
$("#msgDiv", dialog).html(msg);
}
})
})
再來是后台代碼
@Path("/upload")
@POST
@NoCache
@Consumes("multipart/form-data")
public ExtJSResponse upload(@Context HttpServletRequest request) {
ExtJSResponse resp = new ExtJSResponse(true);
final String id = request.getParameter("id");
final AmlSuspectcaseAttach attach = new AmlSuspectcaseAttach();
boolean isMultipart= ServletFileUpload.isMultipartContent(request);
if(isMultipart){
//構造一個文件上傳處理對象
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
@SuppressWarnings("rawtypes")
Iterator items;
try{
checkPermission(Permissions.AML_SUSPECT_CASE);
//解析表單中提交的所有文件內容
items = upload.parseRequest(request).iterator();
while(items.hasNext()){
FileItem item = (FileItem) items.next();
if(!item.isFormField()){
//取出上傳文件的文件名稱
String name = item.getName();
logger.info("上傳文件的大小為:[{}]",item.getSize());
//取得上傳文件以后的存儲路徑 final String suffix = name.substring(name.lastIndexOf('.') + 1, name.length());
int fsize = fileSize*1024*1024;
if(fileSuffix.contains(suffix)){
if(item.getSize() < fsize){
Long attachId = null;
if(!StringUtils.isEmpty(name)){
attach.setName(name);
}
if(!StringUtils.isEmpty(id)){
attach.setCaseid(Long.parseLong(id));
attachId = suspectCase.insertAttch(attach);
System.out.println("attach:"+attachId);
}
if(resp.isSuccess()){
//上傳文件以后的存儲路徑
logger.info("上傳文件:[{}]",attachId+"."+suffix);
String Path= amlPath + File.separatorChar + attachId;
File file =new File(amlPath);
//如果文件夾不存在則創建
if (!file.exists() && !file.isDirectory())
{
file.mkdir();
}
//上傳文件
logger.info("上傳文件的路徑為:[{}]",Path);
File uploaderFile = new File(Path);
item.write(uploaderFile);
}
}else{
logger.info("上傳文件大小不能超過2M");
resp.setSuccess(false);
resp.setErrorMsg("上傳文件大小不能超過2M");
}
}else{
logger.info("文件格式不正確,請選擇doc、docx、xls、xlsx、png、gif、jpg、jpeg、bmp后綴文件!");
resp.setSuccess(false);
resp.setErrorMsg("文件格式不正確,請選擇doc、docx、xls、xlsx、png、gif、jpg、jpeg、bmp后綴文件!");
}
}
}
}catch(Exception e){
e.printStackTrace();
resp.setSuccess(false);
resp.setErrorMsg("文件上傳失敗");
}
}
return resp;
}
@Path("/uploadTotal")
@POST
@NoCache
@Consumes("multipart/form-data")
public ExtJSResponse uploadTotal(@Context HttpServletRequest request) {
ExtJSResponse resp = new ExtJSResponse(true);
@SuppressWarnings("unused")
InputStream instream = null;
try {
checkPermission(Permissions.AML_SUSPECT_CASE);
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator fileIterator = upload.getItemIterator(request);
while (fileIterator.hasNext()) {
FileItemStream item = fileIterator.next();
if ("file".equals(item.getFieldName())){
instream = item.openStream();
break;
}
}
StringBuilder total = new StringBuilder();
resp.put("totalInfo", total);
} catch (Exception e) {
getLogger().warn(e.getMessage(), e);
resp.setSuccess(false);
resp.setErrorMsg(e.getLocalizedMessage());
}
return resp;
}
其中uploadTotal方法是在文件上傳之前先對文件進行解析,下面貼上我的上傳效果圖,我這里是用的frame彈窗

解析完再點擊確認上傳之后就完成了。
