附加上传、下载自己没有真正在项目中自己写过,都是直接调用的框架内现成的方法,所以每次遇到项目框架不提供方法时自己心里发怯,此处记录一下项目中自己写的附件上传,下载方法,以及下载时前段遇到的坑;
附件上传
这里提供的是个接口,前段采用异步的方式进行的上传;
我们项目的接口书写方式有些奇怪,和经常用的方法不太一样;
前段用的是layui的附件上传组件,写起来比较方便;
/**
* 附件上传 单文件上传
* @param request
* @param response
* @param
*/
@RequestMapping(value = "uploadFile", method = RequestMethod.POST)
public void uploadFile(HttpServletRequest request, HttpServletResponse response){
{
Result result = new Result();
String json = "";
Claims b = JWTUtil.parseJWT(request.getParameter("token"), ConfigLoader.baseSecurity);
String accountName = (String) b.get("accountName");
Accounts account = accountServicesImpl.getEntityBySql("select * from accounts where account_name = '" + accountName + "' and del_flag = 0", null, Accounts.class);
User user = accountServicesImpl.getUserByAccount(account.getId());
File file = null;
try{
// MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFilefile = multipartRequest.getFile("file");
String filename = "";
Long size = 0l;
// MultipartFile multipartFilefile=null;
// Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
// for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
// multipartFilefile = entry.getValue();
filename = multipartFilefile.getOriginalFilename();
size = multipartFilefile.getSize();
// }
// 从数据字典中获取上传路径
String upconfigPath = "";
List<CategoryAttributes> leiMuAtt = new ArrayList<CategoryAttributes>();
leiMuAtt = ConfCache.attributeConfMap.get("Path_Upload");
if (leiMuAtt != null && leiMuAtt.size() > 0) {
for (CategoryAttributes tr : leiMuAtt) {
CategoryAttributes c = (CategoryAttributes) tr;
if (c.getCategoryAttributesName().equals("上传公共路径")) {
upconfigPath = c.getCategoryAttributesValue();
}
}
}
// String downconfigPath = upconfigPath.substring(upconfigPath.lastIndexOf("/") + 1);
// 从数据字典中获取下载路径
// String downconfigPath = "";
// List<CategoryAttributes> leiMuAttt=new ArrayList<CategoryAttributes>();
// leiMuAttt=ConfCache.attributeConfMap.get("Path_Download");
// if(leiMuAtt!=null && leiMuAttt.size()>0){
// for (CategoryAttributes tr : leiMuAttt) {
// CategoryAttributes c = (CategoryAttributes)tr;
// downconfigPath=c.getCategoryAttributesValue();
// break;
// }
// }
// 获取日期时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String date = sdf.format(new Date());
SimpleDateFormat sdft = new SimpleDateFormat("HHmmssSSS");
String timeValue = sdft.format(new Date());
// 上传到服务器的路径(数据字典上传配置+“/attachment/”附件文件夹+日期)
String dir = "";
dir = upconfigPath + "/taskfiles/" + date + "/";
// downconfigPath = downconfigPath + "/taskfiles";
File directory = new File(dir);
// 目录不存在,创建目录
if (!directory.exists()) {
directory.mkdir();
}
// 原文件信息
System.out.println(filename);
try {
filename = java.net.URLDecoder.decode(filename, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(filename);
String oldfilename = filename.substring(filename.lastIndexOf("\\") + 1);
String sourcename = oldfilename.substring(0, oldfilename.lastIndexOf(".")); // 文件名
String ofileType = oldfilename.substring(oldfilename.lastIndexOf(".") + 1); // 文件后缀
Long ofileSize = size;
// 新路径(dir配置路径+时间戳.格式后缀)
String newfile = dir + timeValue + "." + ofileType;
file = new File(newfile);
Attachment attachment = new Attachment();// 记录上传的信息
try {
if (!file.exists()) {
// Accounts account = (Accounts) ss.getAttribute("login_user");
attachment.setFileName(sourcename);
attachment.setDir(dir); // 下载时的相对路径
attachment.setFileSize(ofileSize);
attachment.setPhysicalName(timeValue + "");
attachment.setCreateTime(new Date());
attachment.setCreateUserId(account.getId());
// attachment.setAttachedTable(attachedTable);
attachment.setStatus(0);
attachment.setFileType(0);
// attachment.setRecordId(recordId);
attachment.setExt(ofileType);
attachment.setUploadPath(dir + timeValue + "." + ofileType);
attachmentServicesImpl.save(attachment);
}
// FileUtils.copyFile((File) files.get(0), file);// 上传 (复制文件)
FileUtils.copyInputStreamToFile(multipartFilefile.getInputStream(),file);
} catch (IOException e1) {
e1.printStackTrace();
throw new RuntimeException("文件上传失败!");
}
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\"code\":");
sb.append(0 + ",");
sb.append("\"msg\":");
sb.append("\"上传成功!\",");
sb.append("\"data\":");
sb.append(JsonUtil.object2json(attachment));
sb.append("}");
json = sb.toString();
}catch(Exception e){
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\"code\":");
sb.append(1 + ",");
sb.append("\"msg\":");
sb.append("\"上传失败!\",");
sb.append("}");
json = sb.toString();
}
this.print(json,response);
}
其中的难点在于如何从HttpServletRequest 中获取到附件信息,也就是MultipartFile,一开始用的是下面的方法
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> files = multipartRequest.getFiles("files");
但是这个方法会报错,提示不能直接转换成MultipartHttpServletRequest ,所以就换成了最上边的方法转换,这样换过之后还是不行,又提示multipartRequest.getFiles("files")内的数量为0,也就是没有附件,所以就用以下方法:
MultipartFile multipartFilefile=null;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
multipartFilefile = entry.getValue();
filename = multipartFilefile.getOriginalFilename();
size = multipartFilefile.getSize();
}
上传路径是直接到数据字典内取得;
注:上边两个是上传多文件的方法,后期做了修改,代码中的才是单文件上传;
这里用到了一个工具类org.apache.commons.io包下的FileUtils,里面有很多操作文件的方法,可以在网上查到,这里就不列举了;
这边从数据字典中获取的上传路径是/u06/upload,所以文件上传后入库的路径也是这个;另外数据库中还存入和/u06/upload/日期/文件名.houzhui,下载时就直接取用这个字段了,文件上传成功后,最后上传到了与我项目workspace同级的/u06/upload文件夹下;
附件下载
先贴上后台controller代码:
/**
* 附件下载
* @param request
* @param response
* @param
*/
@RequestMapping(value = "downloadFile")
public void downloadFile(HttpServletRequest request, HttpServletResponse response, String id){
Result result = new Result();
try{
Base base = new Attachment();
base.setId(id);
String ids = request.getParameter("id");
Attachment attachment = (Attachment) attachmentServicesImpl.getBean(base);
String fileName = attachment.getFileName() + "." + attachment.getExt();
// String dir = attachment.getDir();
String path = attachment.getUploadPath();
File sourceFile = new File(path);
if (!sourceFile.exists()) { throw new Exception("您下载的资源已不存在"); }
BufferedInputStream in = null;
ServletOutputStream out = null;
try {
// fileName = URLEncoder.encode(fileName, "UTF-8"); //解决下载文件名乱码
response.reset();
response.setCharacterEncoding("UTF-8");
// response.setContentType("application/octet-stream");
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
in = new BufferedInputStream(new FileInputStream(sourceFile));
out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
throw new Exception(fileName + " 下载出错,若有问题请与管理员联系");
} finally {
out.close();
in.close();
}
result.setSuccess(true);
result.setMessage("下载成功");
}catch(Exception e){
e.printStackTrace();
result.setSuccess(false);
result.setMessage("下载失败!"+e.getMessage());
}
// this.print(result.toString(),response);
}
说一说下载时遇到的坑吧,下载时我是通过点击<a>标签,然后触发一个ajax调用后台下载的,但是这样页面没有提示任何下载提示,也不报错,但是response 内有文件的内容,在网上查了一下才知道,附件下载是不能用ajax来搞的,好像ajax返回的是字符类型的结果,浏览器没办法解析response内的附件,所以必须换方法了,看了别人的方法有用window.href.location的,也有用a标签内使用download 属性的,我也试了一下这个属性,下载的不是原文件,是以download 命名的空文件,然后又在href属性内直接写后台映射地址的,导致页面跳转了,也没有附件下载;最后就用了formdata提交的方式请求,这样页面也不会跳转,还能下载到附件了;
粘上前段代码;
<div class="layui-upload-list">
<table class="layui-table">
<thead>
<tr><th>文件名</th>
<th>大小</th>
<th>状态</th>
<th>操作</th>
</tr></thead>
<tbody id="demoList"></tbody>
</table>
</div>
$("#demoList").append('<tr>' +
'<td><a href="#">'+data.list[i].fileName+'.'+data.list[i].ext+'</a></td>' +
'<td>'+((data.list[i].fileSize)/1014).toFixed(1)+'kb</td>' +
'<td><span style="color: #5FB878;">上传成功</span></td>' +
'<td>' +
'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'+
'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete-exist">删除</button>' +
'</td>' +
'<td class="layui-hide">'+data.list[i].id+'</td>' +
'</tr>')
$("#demoList").find("a").on('click',function (e) {
var p_tr = $(this).parent().parent();
//删除附件数组内的附件id
var tds = p_tr.children();
//找到该附件的主键
var id = tds.eq(4).text();
var $eleForm = $("<form method='get'></form>");
$eleForm.attr("action","/CenterChainTaskController/downloadFile");
$(document.body).append($eleForm);
$eleForm.append('<input type="text" name="id" value="'+id+'">')
//提交表单,实现下载
$eleForm.submit();
})