基于uploadify上传和 servlet 的下载
由于工作需要 暂时快速的选定了uploadify作为文件上传插件。至于下载就匆忙的用servlet来实现
首先到uploadify官网下载需要的Js文件
然后需要自己手写一个Js 来调用 uploadify.js 重点只说上传 其他辅助功能方法不细说
$(function() {
uploadify();
});
var idSeq = 0;
var filename = [];
function uploadify() {
$("#file_upload")
.uploadify(
{
'height' : 22,
'width' : 65,
'buttonText' : '添加附件',
'swf' : rsc
+ '/static/jquery-uploaddify/uploadify.swf?ver='
+ Math.random(),
'uploader' : ctx + '/rest/upload/uploadFile?cat=file',
'auto' : false,
'formData' : {
"JSESSIONID" : $("#sessionUID").val() // jssessionid 为了解决火狐下的问题。
},
'fileSizeLimit' : '1000000KB',
'fileTypeExts' : '*.doc; *.jpg; *.rar',
'cancelImg' : ctx + '/static/img/uploadify-cancel.png',
'uploadLimit' : 10,
'onSelect' : function(file) {
startUpload();
},
上传成功后 我自己需要这些返回信息,所以拼了个这种格式的字符串返回,其中夹杂HTML标签是为了显示用
'onUploadSuccess' : function(file, data, response) {
var result = $.parseJSON(data);
var filepatch = encodeURI(result.obj.filepatch);// 数据库保存路径
var as = result.obj.fileNames;// 文件名称
filename.push(result.obj.filepatch
+ result.obj.fileNames);// 在邮件中保存文件路径从文件夹开始
$('#file').val(filename.join(","));
var updTableHtml = $("#updTable tbody").html();
idSeq++;
$('#uploadifyTags').addTag(as.substr(15, as.length));
updTableHtml += "<tr id='tld"
+ idSeq
+ "'><td align='left'>"
+ as.substr(15, as.length)
+ " <a href='javascript:void(0)' style='text-decoration:none;' onclick=deleteTR('"
+ 'tld' + idSeq + "','" + filepatch + "','"
+ as + "')>删除</a></td></tr>";
$("#updTable tbody").html(updTableHtml);
},
});
}
function startUpload() {
console.debug($('#file_upload'));
$('#file_upload').uploadify('upload', '*');
}
功能需要的删除方法,不细说,
function deleteTR(id, patch, filename) {
$("#" + id).remove();
$.post(ctx + '/rest/upload/deleteFile?path=' + patch + filename
+ "&cat=file");
console.debug(path+"|"+filename);
}
然后是上传前台页面- 其实就是一个简单的控件。updtable table 是用来显示用户已经上传的文件,显示 的是上面uploadify.js 中onUploadSuccess 函数返回的那段字符串
<tr>
<td colspan="2" align="left"><input id='sessionUID' value='<%=session.getId()%>' type="hidden" /> <input type="file"
name="uploadify" id="file_upload" />
<!-- <input type="text" class="tags" id="uploadifyTags"> -->
<table id="updTable">
<tr>
</tr>
</table>
</td>
</tr>
最后面是 java代码 因为我这里是公用的一个上传方法,所以保存路径是作为参数获取的,每个模块的保存路径都不同,不需要的话写死了就行 ,为了不使上传后的文件命名重复,保存路径的文件夹用时间命名,上传文件 在文件名前又拼接了时间 截取到秒 来命名。显示的时候再截取掉就可以了
@RequestMapping("/uploadFile")
// @RolesAllowed(AuthorityDefine.ROLE_USER) //为解决火狐下jsessionid问题,因为这里我用了spring security 如果设置权限 则无法调用上传方法
@ResponseBody
public ReturnObject uploadFile(String cat,HttpServletRequest request,
HttpServletResponse response) throws IOException{
String basePath = Global.BASE_UPLOAD_FOLDER; //获取基础路径
String propValue = Global.getProp().getProperty("upload.path." + cat);//获取对应文件夹
if (StringUtils.isBlank(propValue)){ throw new InvalidParameterException(
"cat参数错误,没有找到[upload.path." + cat + "]的配置"); }
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
Map<String,MultipartFile> fileMap = multipartRequest.getFileMap();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
SimpleDateFormat sp = new SimpleDateFormat("yyyyMMdd");
String ctxPath = basePath + "/" + propValue + File.separator+sp.format(new Date())+"/";//完整路径
String ctxPathView = sp.format(new Date()) + "/";// 用于在数据库存储的路径-从文件夹开始
String ymd = sdf.format(new Date());
// 如果不存在,创建文件夹
File file = new File(ctxPath);
if (!file.exists()){
file.mkdirs();
}
ReturnObject ro = new ReturnObject();
String fileNames = "";
for (Map.Entry<String,MultipartFile> entity : fileMap.entrySet()){
MultipartFile mf = entity.getValue();
String fileName = mf.getOriginalFilename();
fileName = ymd + "_" + fileName;
File uploadFile = new File(ctxPath + fileName);
try{
FileCopyUtils.copy(mf.getBytes(),uploadFile);
fileNames += fileName + ",";
}
catch (IOException e){
e.printStackTrace();
ro.setSuccess(false);
ro.setMsg(e.getMessage());
return ro;
}
}
if (fileNames.endsWith(",")){
fileNames = fileNames.substring(0,fileNames.length() - 1);
}
ro.setSuccess(true);
ro.setMsg("上传文件成功");
HashMap<String,Object> hsfiled = new HashMap<String,Object>();
hsfiled.put("fileNames",fileNames);
hsfiled.put("filepatch",ctxPathView);//数据库保存路径(从时间开始截取的)
ro.setObj(hsfiled);
return ro;
}
附件下载---------------------------------------------------------------------------------------------------
首先前台简单,
<div data-options="region:'east',border:true" style="overflow: hidden; padding: 5px; width:250px">
<label><font size="2" ><b>附件下载区</b></font></label>
<hr>
<table id="downfile">
<tr></tr>
</table>
</div>
var row = $('#messageDG').datagrid('getSelected');
if (row.file !=0 && row.file !=null) {
var updTableHtml = $("#downfile tbody").html();
var arry = row.file.split(",");
for ( var i = 0; i < arry.length; i++) {
updTableHtml += "<tr><td>"
+ arry[i].substr(24, arry[i].length)
+ " <a href='"
+ rsc
+ "/rest/upload/download?path="
+ arry[i]
+ "&cat=file' style='text-decoration:none;'> 下载</a></td></tr>";
}
$("#downfile tbody").html(updTableHtml);
}
java代码
@RequestMapping("/download")
@RolesAllowed(AuthorityDefine.ROLE_USER)
public void download(String path,String cat,HttpServletRequest request,
HttpServletResponse response){
try{
File file = new File(Global.BASE_UPLOAD_FOLDER+"/"+ cat+"/"+path);
String filename = file.getName();
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition","attachment;filename="
+ new String(filename.getBytes("utf-8"),"ISO-8859-1"));
response.addHeader("Content-Length","" + file.length());
response.setContentType("application/octet-stream");
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
}
catch (IOException ex){
ex.printStackTrace();
}
}
PS: 上传提到了删除,附加删除代码
@RequestMapping("/deleteFile")
@RolesAllowed(AuthorityDefine.ROLE_USER)
@ResponseBody
public ReturnObject deleteFile(String path,String cat){
ReturnObject ro = new ReturnObject();
String removePath = Global.BASE_UPLOAD_FOLDER+"/"+ cat+"/"+path;
File file = new File(removePath);
if (file.isFile() && file.exists()){
file.delete();
ro.setMsg("删除成功");
ro.setSuccess(true);
}
else{
ro.setMsg("删除失败");
ro.setSuccess(false);
}
return ro;
}