html:
<span id="bidFileSpan" class="btn btn-primary fileinput-button">
<span id="divUpload2_text">上传</span>
<input type="file" id="inputfile" name="inputfile"/>
</span>
js:
//初始化控件,在那个span中只要有上传都会执行下面的方法。
function initUploadBidFile(){
$("#bidFileSpan").fileupload({
url: commons.getPath()+'/file/uploadFile.do?type=2',
dataType : 'json',
sequentialUploads: true
}).bind('fileuploadprogress', function (e, data) {
$("#bidFileUploading").show();
}).bind('fileuploaddone', function (e, data) {
if (commons.checkResponse(data.result)) {
var html = "<input type=\"hidden\" id=\"biddocumentInfoFileInformationId\" value=\""+data.result.fileInformation.objectId+"\" /><label for=\"lastname\" class=\"col-sm-0 control-label\"><a href=\""+commons.getPath()+"/download?filePath="+data.result.fileInformation.relativePath+"&fileName=bidFile\" target=\"_blank\">招标文件</a></label><button type=\"button\" class=\"btn btn-danger\" οnclick=\"deleteBidFile();\">删除</button>";
$("#payFile").empty();
$("#payFile").append(html);
}
$("#bidFileUploading").hide();
});
}
java:Controller
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回
@RequestMapping(value = "/uploadFile.do", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
public ModelAndView uploadFile(ModelAndView mav, MultipartHttpServletRequest request, Integer type) {
try {
FileInformation fileInformation = UploadFileUtil.uploadFileOfMultipartHttpServletRequest(
request, checkFileType(type), achieveFileErrorMessage(type));
mav.addObject("fileInformation", fileInformation);
} catch (Exception e) {
log.error("文件上传悲剧。", e);
mav.addObject(SysErrorCode.RESPONSE_CODE, SysErrorCode.FILE_UPLOAD_CODE);
mav.addObject(SysErrorCode.RESPONSE_MESSAGE, SysErrorCode.DEFAULE_FILE_UPLOAD_MESSAGE);
}
return mav;
}
service:
public static FileInformation uploadFileOfMultipartHttpServletRequest(MultipartHttpServletRequest request,
String[] checkPattern, String errorMessage) {
Iterator<String> itr = request.getFileNames();
MultipartFile mpf = null;
FileInformationService fileInformationService = IocBeanFactory.getBean(FileInformationService.class);
FileInformation fileInformation = null;
while (itr.hasNext()) {
String next = itr.next();//页面上的name属性从而得到value就是所谓的文件内容
mpf = request.getFile(next);//文件的内容
// 后台验证文件格式
Assert.isFilePatterns(mpf, checkPattern, errorMessage);
File file = new File(mpf.getOriginalFilename());
try {
mpf.transferTo(file);//把文件写入到新的文件,
fileInformation = fileInformationService.upload(file);//把文件上传到ftp中
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file.exists()) {
file.delete();
}
}
}
return fileInformation;
}