一、上传附件
1、jsp页面
<div style="padding-top: 2px;" class="col-md-3 boder-line">
<input type="button" id="brows1" value="浏览" onclick="chooseFile1()" style="float: left;"/>
<input type="text" readonly="readonly" id="filePath1" value="${commonAttachments[0].fileName }" style="width: 232px; position: absolute; top: 4px; left: 66px; border: 0px;"/>
<input type="file" name="file" id="docFile1" style="display: none;" onchange="putValue1(this)"/>
</div>
<script type="text/javascript">
/* 点击浏览按钮 */
function chooseFile1(){
$("#docFile1").click();
}
function putValue1(target,id){
//检验是否为可上传的文件类型
fileChange(target,id);
var file = $("#docFile1").val();
document.getElementById("filePath1").value=file.substring(file.lastIndexOf("\\")+1);
}
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
function fileChange(target,id) {
var fileSize = 0;
var filetypes =[".pdf",".PDF"];
var filepath = target.value;
var filemaxsize = 1024*5;//5M
if(filepath){
var isnext = false;
var fileend = filepath.substring(filepath.lastIndexOf("."));
if(filetypes && filetypes.length>0){
for(var i =0; i<filetypes.length;i++){
if(filetypes[i]==fileend){
isnext = true;
break;
}
}
}
if(!isnext){
alert("只支持上传PDF类型附件!");
target.value ="";
return false;
}
}else{
return false;
}
if (isIE && !target.files) {
var filePath = target.value;
var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
if(!fileSystem.FileExists(filePath)){
alert("附件不存在,请重新输入!");
return false;
}
var file = fileSystem.GetFile (filePath);
fileSize = file.Size;
} else {
fileSize = target.files[0].size;
}
var size = fileSize / 1024;
if(size>filemaxsize){
alert("附件大小不能大于"+filemaxsize/1024+"M!");
target.value ="";
return false;
}
if(size<=0){
alert("附件大小不能为0M!");
target.value ="";
return false;
}
}
</script>
2、controller层接收
@RequestMapping(value="save", method=RequestMethod.POST)
@ResponseBody
public Operate save(@RequestParam("file") MultipartFile[] multipartFiles,
CosEntrust cosEntrust, HttpServletRequest request) {
Operate op = new Operate();
Long cosEntrustId = mapper.querySeq();
WebUserInfo user = getSessionUser(request);
//保存附件
if(multipartFiles.length > 0 && StringUtils.isNotEmpty(multipartFiles[0].getOriginalFilename())) {
commonAttachmentService.uploadFile(multipartFiles, Constants.COS_ENTRUST, cosEntrustId, user);
}else {
op.setOperResult("N");
op.setOperMsg("附件不能为空");
return op;
}
return op;
}
3、service层
@Override
@Transactional(value="transactionManager",rollbackFor=Exception.class)
public List<CommonAttachment> uploadFile(MultipartFile[] multipartFiles, String businessType, Long businessId, WebUserInfo user) {
List<CommonAttachment> list = new ArrayList<>();
try {
if (multipartFiles != null) {
CommonAttachment attachedFile = new CommonAttachment();
attachedFile.setBusinessType(businessType);
attachedFile.setCreateUser(user.getUser_id());
attachedFile.setBusinessId(businessId);
attachedFile.setCreateTime(new Date());
attachedFile.setLastUpdateUser(user.getUser_id());
attachedFile.setLastUpdateTime(new Date());
for (MultipartFile multipartFile : multipartFiles) {
String dateString = DateUtil.currentDateFormat("yyyy-MM-dd");
String filePath = path + "/"+ dateString;
File fileFolder = new File(filePath);
if(!fileFolder.exists()){
fileFolder.mkdirs();
}
String[] split = multipartFile.getOriginalFilename().split("\\.");
String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + split[split.length-1];
//将文件写出到指定目录
multipartFile.transferTo(new File(fileFolder, newFileName));
//更新数据库
attachedFile.setId(mapper.querySeq());
attachedFile.setFileName(multipartFile.getOriginalFilename());
attachedFile.setFilePath(dateString);
attachedFile.setUploadName(newFileName);
attachedFile.setFileSize(multipartFile.getSize());
mapper.insert(attachedFile);
list.add(attachedFile);
}
}
} catch (Exception e) {
e.printStackTrace();
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw,true));
String str = sw.toString();
Log4JUtil.error(FileUtil.class, str);
throw new SystemException("common.fileUploadFailed");
}
return list;
}
二、下载附件
1、前端页面的bootstrap表格
{
title : "<fmt:message key='cos.entrust.attachment' />",
formatter: function (value, row, index) {
//return '<a href="' + row.ENTRUSTACCESSORY + '">查看附件</a>';
var id = row.ID;
var url = ctx+ '/common/attachedFile/downloadFile?id='+id;
return['<div id="fjdiv"><a href="'+url+'"><u>查看附件</u></a></div>'].join("");
}
},
2、controller层
@RequestMapping(value = "/downloadFile")
public Operate downloadAttachedFile(HttpServletRequest request,HttpServletResponse response,CommonAttachment commonAttachment){
try{
if(commonAttachment == null){
commonAttachment = new CommonAttachment();
}
InputStream inputStream=null;
OutputStream outputStream=null;
Long id =commonAttachment.getId();
commonAttachment= commonAttachmentServiceI.queryAttachmentById(id);
File file=new File(Constants.UPLOAD_PATH+"/"+commonAttachment.getFilePath()+"/"+commonAttachment.getUploadName());
String fileName = commonAttachment.getFileName();
String userAgent=request.getHeader("User-Agent").toUpperCase();
if(userAgent.contains("MSIE")||userAgent.contains("TRIDENT")||userAgent.contains("EDGE")){
// ie兼容性
fileName = URLEncoder.encode(fileName, "UTF-8");
fileName = fileName.replace("+", "%20"); // IE下载文件名空格变+号问题
}else{
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("Expires", 0);
response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + file.length());
response.setContentType("application/octet-stream;charset=UTF-8");
inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
inputStream.close();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
三、附件表
应包含如下字段:
主键ID、原文件名、文件大小、上传后的文件名(一般用UUID)、文件路径、文件类型等