Dropzone 简介
Dropzone 是一个开源的 JavaScript 库,提供文件的异步上传功能,并支持拖拽上传功能
页面引用
<!--DropZone BEGIN css-->
<link href="/static/assets/global/plugins/dropzone/dropzone.min.css" rel="stylesheet" type="text/css" />
<link href="/static/assets/global/plugins/dropzone/basic.min.css" rel="stylesheet" type="text/css" />
<!--DropZone END-->
<!--DropZone BEGIN js-->
<script src="/static/assets/global/plugins/dropzone/dropzone.min.js" type="text/javascript"></script>
<!--DropZone END-->
在放上传文件的地方 写入div并初始化即可出现上传
<div class="dropzone dropzone-file-area" id="my-dropzone" >
<h5 class="sbold">点击方框上传图片</h5>
<!--<img id="img" src="${item.image}" alt="看不清">-->
</div>
Dropzone代码如下(Wang Editor部分可忽略--如第二个参数等部分)
//Dropzone初始化与配置
Dropzone.options.myDropzone = {
//上传请求地址
url: "/upload",
//最大上传文件数
maxFiles:"1",
//提示信息默认有 设置提示为空
dictDefaultMessage: "",
//传递过去的参数 取别名file 默认为file
paramName: "uploadFile",
//取消自动上传 false
autoProcessQueue:true,
init: function() {
//把autoProcessQueue设为false可设置提交图片的点击事件
//var submitButton = document.querySelector("#sb");
this.on('success', function (files, data) {
//文件上传成功之后的操作 data为客户端返回的json数据
$("#image").val(data.path);
//$("#img").css("display","none");
});
/*//点击事件才能上传
submitButton.addEventListener('click',function(){
//点击上传文件
this.processQueue();
})*/
}
};
服务端接收请求的处理 Example
@Controller
public class UploadController {
//保存文件的目录
private static final String FILE_UPLOAD_PATH = "static" + File.separator + "upload";
/**
* 图片上传
* @return
*/
@ResponseBody
@RequestMapping(value = "/upload")
public Map<String, Object> upload(MultipartFile uploadFile,MultipartFile[] editorFileName,HttpServletRequest request) throws IOException {
String path=null;
Map<String,Object> map= Maps.newHashMap();
//DropZone上传
if(uploadFile!=null){
path = getString(uploadFile, request);
map.put("path",path);
}
//Wang Editor上传
else{
List<String> paths = Lists.newArrayList();
for (MultipartFile editorFile : editorFileName) {
path = getString(editorFile, request);
paths.add(path);
}
map.put("errno",0);
map.put("data",paths);
; }
return map;
}
private String getString(MultipartFile uploadFile, HttpServletRequest request) throws IOException {
//获取upload目录在服务器的绝对路径
String realPath = request.getServletContext().getRealPath(FILE_UPLOAD_PATH);
File file=new File(realPath);
if(!file.exists()){
file.mkdirs();
}
//文件名
String fileName=uploadFile.getOriginalFilename();
//保存的文件名
String saveFileName= UUID.randomUUID().toString().replaceAll("-","")+fileName;
file=new File(file, saveFileName);
//保存文件
uploadFile.transferTo(file);
//将图片绝对路径返回给前端
return String.format("%s://%s:%s/%s/%s", request.getScheme(),request.getServerName(),request.getServerPort(),FILE_UPLOAD_PATH,saveFileName);
}
}
网友评论