页面
<!--引入CSS-->
<link rel="stylesheet" type="text/css" href="${ctx}scripts/webuploader-0.1.5/webuploader.css">
<!--引入JS-->
<script type="text/javascript" src="${ctx}scripts/webuploader-0.1.5/webuploader.js"></script>
<div id="uploader-demo">
<div id="filePicker">选择图片</div>
</div>
<div id="fileList" class="uploader-list"></div>
<script type="text/javascript">
var uploader = WebUploader.create({
auto: true,
swf: '${ctx}scripts/webuploader-0.1.5/Uploader.swf',//对应引入的文件
server: '${ctx}/article/uploadFile',//对应你的后台接收方法
pick: {
id: '#filePicker',
multiple:false,
label: '点击选择图片'
},
fileNumLimit: 1,
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});
uploader.reset();
//生成缩略图和上传进度
uploader.on("fileQueued", function(file) {
$("#fileList").append("<div id='" + file.id + "'><img/><div><span class='percentage'><span></div></div>")
uploader.makeThumb(file, function(error, src) {
if (error) {
$("#" + file.id).find("img").replaceWith("<span>无法预览 </span>");
} else {
$("#" + file.id).find("img").attr("src", src);
}
});
}
);
uploader.on( 'uploadSuccess', function( file , response) {
var imgurl = response._raw; //上传图片的路径
$('#picpath').val(imgurl);
});
uploader.on('click', '.remove-this', function(file) {
uploader.removeFile( file );
})
</script >
java后台
//上传文件
@RequestMapping(value = "/uploadFile")
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile attach, HttpServletRequest request){
String basepath ="E:/1111/"; //request.getSession().getServletContext().getRealPath("/");
String functionPath = request.getParameter("functionPath");
if(functionPath == null || "".equals(functionPath)) {
functionPath = "other";
}
String name = attach.getOriginalFilename();
String type = name.substring(name.lastIndexOf(".") + 1);
if (!FileUploadUtil.checkFileName(type, FileUploadUtil.IMG_SUFFIX)) {
return "error";
}
String replyPath = FileUploadUtil.uploadImg(attach, functionPath, basepath);
return replyPath;
}
/**
* 上传图片
* @param attach MultipartFile类型图片
* @param functionPath 功能路径
* @return error:出异常;图片保存后相对路径
*/
public static String uploadImg(MultipartFile attach,String functionPath,String basepath){
String nowPath=FormatDate.toShortFormat(new Date());
String path = basepath + "upload/img/"+ functionPath+"/"+nowPath +"/";
File dicimg = new File(path);
if (!dicimg.exists()) {
dicimg.mkdirs();
}
String name = attach.getOriginalFilename();
String type = name.substring(name.lastIndexOf(".") + 1);
String now=System.nanoTime()+"";
String newName=now+"."+type;
String filePath = path + newName;
FileOutputStream write = null;
try {
write = new FileOutputStream(new File(filePath));
write.write(attach.getBytes());
write.flush();
return "/upload/img/" + functionPath +"/"+ nowPath +"/" + newName;
} catch (Exception e) {
e.printStackTrace();
return "error";
} finally{
try {
if(write !=null){
write.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}