uploadify是一个jquery插件,用来实现文件上传的功能。
20160724 看起来感觉挺麻烦的
一般会买一个html5版的。
html
<input id="custom_file_upload" type="file" name="Filedata" />
js
//关键是路径要设置正确
//总会发起请求:http://localhost:8080/jyxt/img/uploadify-cancel.png,不知道从哪发起的?
function inituploadimge(){
$('#custom_file_upload1').uploadify({
'swf' : path_t+'js/uploadify.swf',
//后台处理程序的URL
'uploader' : path_t+'manage/fileupload/',
'method' : "post",
'use_query_string': true,
'post_params': {
"hello" : encodeURI("你好,我是","utf-8"),
"baseurl" : "userfiles/images/linkimages/"
},
'cancelImage' : path_t+'images/cancel.png',
'buttonText' : '浏览',
'buttonImg' : path_t+'images/sel.png',
'queueID' : 'custom-queue1',
'fileTypeExts':'*.jpg;*.gif;*.png;',
'fileTypeDesc':'图片文件',
'removeCompleted': true,
'onSelectOnce' : function(event,data) {
$('#custom-queue1').text('文件上传中!');
},
'onUploadSuccess' : function(file, data, response) {
$('#custom-queue1').text('上传成功');
$('#picUrl').attr("value",data);
}
});
}
controller
//存储的路径设置比较麻烦
//1、savePath如何设置基础的路径?baseurl是传过来的,相对于webcontent的路径。
//2、保存时,会保存到tomcat下,应该保存在jyxt中呀?
//3、saveFile.getAbsolute()可以得到文件存储的路径。
//4、request.getServletPath() 是uploader的值
@RequestMapping(value = "/manage/fileupload/", method = RequestMethod.POST)
public void fileUpload(HttpServletRequest request,HttpServletResponse response) throws Exception {
//设置路径
String baseurl=request.getParameter("baseurl");
//路径有问题
String savePath = request.getSession().getServletContext().getRealPath("")+"/"+baseurl; DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac); String filename=""; File f1 = new File(savePath);
if (!f1.exists()) {
f1.mkdirs();
}
List<FileItem> fileList = null;
fileList = (List<FileItem>) upload.parseRequest(request);
Iterator<FileItem> it = fileList.iterator(); String name = "";
String extName = "";
while (it.hasNext()) { FileItem item = it.next();
if (!item.isFormField()) {
name = item.getName();
if (name == null || name.trim().equals("")) {
continue;
}
if (name.lastIndexOf(".") >= 0) {
extName = name.substring(name.lastIndexOf("."));
}
Object[] test = {"gif","png","jpg","doc","docx","xls","xlsx","ppt","pptx","ptf","rar","zip",""};
if(!ArrayUtils.contains(test, extName.toLowerCase().substring(1)))
{
continue;
}
File file = null;
do {
name=DateUtil.getNowDateString();
filename=savePath + name + extName;
file = new File(filename);
} while (file.exists());
File saveFile = new File(filename);
try {
item.write(saveFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
response.getWriter().print(request.getContextPath()+"/userfiles/images/linkimages/"+name+extName);
}
以上代码是可以使用的。不过因为uploadify版本不同,文件路径不同,可能会有问题。只是借此记录一些关键的问题。