前端
-
基本使用
页面要引入jquery和ajaxupload.js
获取ajaxupload.js:链接: https://pan.baidu.com/s/1u23LUnYeoRUPDbqmuKcbDw 密码: kznu
初始化控件:
ajaxupload = new Ajax_upload(btn,settings);
参数说明:
btn(上传文件按钮)
settings(配置项)
常用配置项如下
action:后台接收处理文件的URL
type:get或者post
name:上传文件标识(后台接收)
autoSubmit:是否自动提交
onChange:改变选择文件触发回调函数
onSubmit:提交之前触发回调函数
onComplete:提交完成后触发回调函数
代码示例
/**文件上传*/
uploadFun: function() {
// 上传附件
var btn = $('#uploadBtn'), interval;
ajaxupload = new Ajax_upload(btn,{
action : 'fastdfs/uploadFile.do',
type: 'POST',
name : 'file',
autoSubmit : true,
onChange: function(file, ext){
// if (!(ext && /^(xls|xlsx|XLS|XLSX)$/.test(ext))) {
// layer.msg('您上传的文档格式不对,请重新选择!');
// return false;
// }
// if($('#uploadSpan').html()=='说明:责任人等信息需要手动录入') {
// $('#uploadSpan').html(file);
// layer.msg('文件上传成功!');
// }
},
onSubmit : function(file, ext) {
debugger;
if($("#fjxxs").val()&&$("#fjxxs").val().indexOf(file)>0){
layer.msg('文件名重复');
return false;
}
btn.text('上传中...');
// var parm = {
// zrdw: $('#zrdw').val(),
// zrdwmc: $('#zrdwmc').val(),
// zrr: $('#zrr').val(),
// zrrlxdh: $('#zrrlxdh').val()
// };
// this.setData(parm);
interval = window.setInterval(function() {
var t = btn.text();
if (t.length < 13) {
btn.text(t + ".");
} else {
btn.text('上传中');
}
}, 200);
},
onComplete : function(file, resp) {
window.clearInterval(interval);
btn.text('选择附件');
if(resp=='FILE_SIZE_ERROR'){
layer.msg('上传失败!文件大小不得超过500M');
return;
}
if(resp=='error'){
layer.msg('服务器异常');
return;
}
// resp = resp.replace('<pre style="word-wrap: break-word; white-space: pre-wrap;">',"").replace("</pre>","");
var o = JSON.parse(resp);
if(o.flag) {
var oldfjids =$("#fjids").val();
var oldfjxxs =$("#fjxxs").val();
$("#fjids").val(oldfjids+","+o.id);
$("#fjxxs").val(oldfjxxs+","+o.filename);
var html='<p data-fjid="'+o.id+'" class="btn btn-success" style="color: white">'+o.filename+'</p>'
+'<p class="btn btn-danger scfj" style="color: white;margin-right: 10px">X</p>';
$("#fjdiv").append(html);
$(".scfj").click(function() {
var oldfjids =$("#fjids").val();
var oldfjxxs =$("#fjxxs").val();
var cufjxx=$(this).prev().text();
var cufjid=$(this).prev().data('fjid');
var newfjids=oldfjids.replace(','+cufjid,'');
var newfjxxs=oldfjxxs.replace(','+cufjxx,'');
$("#fjids").val(newfjids);
$("#fjxxs").val(newfjxxs);
$(this).prev().remove();
$(this).remove();
});
layer.msg('上传成功!');
} else {
layer.alert(o.obj, {
icon: 7,
skin: 'layer-ext-moon'
});
}
}
});
},
后台文件上传下载代码示例
文件上传
@RequestMapping(value="/uploadFile.do",method=RequestMethod.POST)
@ResponseBody
public void savePhoto(HttpServletRequest request, HttpServletResponse response) {
MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
PrintWriter writer=null;
try {
// 获取文件
CommonsMultipartFile cf = (CommonsMultipartFile) file;
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
File f = fi.getStoreLocation();
// 输出流
response.setContentType("text/html;charset=UTF-8");
writer = response.getWriter();
// 照片信息为空
if (f == null) {
writer.print("FILE_IS_NULL");
return;
}
// 文件信息
String fileName = file.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
// 判断文件类型
// if ("jpg,jpeg,gif,png,bmp,xlsx".indexOf(fileType) <= -1) {
// writer.println("FILE_TYPE_ERROR");
// return;
// }
// 判断文件大小
Long fileSize = file.getSize();
if (fileSize > 500 * 1024 * 1024L) {
writer.print("FILE_SIZE_ERROR");
return;
}
FileInputStream in = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
in.read(b);
in.close();
// 保存附件信息
String id = fastdfsPool.saveFile(b, fileType);
System.out.println(id);
// 返回的id为:group1/M00/00/43/wKg6QVlFMbizddCIAABaToDNjYI620.jpg
// 保存结果
JSONObject jsonObject = new JSONObject();
jsonObject.put("flag", true);
jsonObject.put("filename", fileName);
jsonObject.put("id", id);
jsonObject.put("fastDfsHttpAddr", fastDfsHttpAddr);
// Result result = new Result();
// result.setSuccess(true);
// result.setId(id);
// result.setMsg(fastDfsHttpAddr+id);
// result.setJson(fileType);
// 结果返回流
writer.println(JSON.toJSONString(jsonObject));
} catch (Exception e1) {
writer.print("error");
e1.printStackTrace();
}
}
文件下载
@RequestMapping("/downloadfile.do")
@ResponseBody
public void downloadfile(HttpServletResponse response,String filename,String fastdfsid) {
try {
byte[] fileById = fastdfsPool.getFileById(fastdfsid);
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + new String(filename.getBytes("gb2312"), "iso8859-1"));
try {
InputStream is=new ByteArrayInputStream(fileById);
//激活下载操作
OutputStream os = response.getOutputStream();
//循环写入输出流
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.flush();
os.close();
is.close();
} catch (Exception e){
throw e;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}