webuploader的一个页面多个上传按钮实例

时间:2023-03-09 23:03:57
webuploader的一个页面多个上传按钮实例

webuploader的一个页面多个上传按钮实例

借鉴一位大佬的demo  附上他的github地址https://github.com/lishuqi

我把他的cxuploader.js改了不需要预览  直接上传图片后拿到回传地址给img标签显示图片

    jQuery(function() {

        uploader = new Array();//创建 uploader数组
// 优化retina, 在retina下这个值是2
var ratio = window.devicePixelRatio || 1,
// 缩略图大小
thumbnailWidth = 100 * ratio,
thumbnailHeight = 100 * ratio,
supportTransition = (function(){
var s = document.createElement('p').style,
r = 'transition' in s ||
'WebkitTransition' in s ||
'MozTransition' in s ||
'msTransition' in s ||
'OTransition' in s;
s = null;
return r;
})();
// 所有文件的进度信息,key为file id
var percentages = {};
var state = 'pedding'; //可行性判断
if ( !WebUploader.Uploader.support() ) {
alert( 'Web Uploader 不支持您的浏览器!如果你使用的是IE浏览器,请尝试升级 flash 播放器');
throw new Error( 'WebUploader does not support the browser you are using.' );
} //循环页面中每个上传域
$('.uploder-container').each(function(index){ // 添加的文件数量
var fileCount = 0;
// 添加的文件总大小
var fileSize = 0; var filePicker=$(this).find('.filePicker');//上传按钮实例
var queueList=$(this).find('.queueList');//拖拽容器实例
var placeholder=$(this).find('.placeholder');//按钮与虚线框实例
var statusBar=$(this).find('.statusBar');//再次添加按钮容器实例
var info =statusBar.find('.info');//提示信息容器实例
// 图片容器
var queue = $('<ul class="filelist"></ul>').appendTo( queueList);
var filePickerid = $(this).find('.filePicker').id; //初始化上传实例
uploader[index] = WebUploader.create({
pick: {
id:filePicker,
class:filePicker,
label: '上传' },
dnd: queueList, //这里可以根据 index 或者其他,使用变量形式
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png,doc',
mimeTypes: 'image/*'
}, // swf文件路径
swf: 'js/Uploader.swf', disableGlobalDnd: true,//禁用浏览器的拖拽功能,否则图片会被浏览器打开 chunked: false,//是否分片处理大文件的上传 server: 'fileUpload.do',//上传地址 fileNumLimit: 1,//一次最多上传文件个数 fileSizeLimit: 10 * 1024 * 1024, // 总共的最大限制10M fileSingleSizeLimit: 3 * 1024 * 1024 , // 单文件的最大限制3M
auto :true, formData: {
token:index//可以在这里附加控件编号,从而区分是哪个控件上传的 }
}); uploader[index].on('uploadSuccess',function(file,response){
alert(JSON.stringify(response));
console.log("file:",file);
console.log("response:",response);
console.log("fileAdress:",response.fileAdress);
var imageid = "#"+response.imageAddr+"_1";
mini.get(response.imageAddr).setValue(response.fileAdress);
placeholder.hide();
queueList.hide();
//document.getElementById(response.imageAddr).value=response.fileAdress;
$(imageid).attr("src",response.fileAdress);
alert("上传成功");
}); //可以在这里附加额外上传数据 uploader[index].on('uploadBeforeSend',function(object,data,header) { //alert("id:"+filePicker.attr("id"));
//获得当前id的长度
var divlen = filePicker.attr("id").length;
//alert("divlen"+divlen);
//截取id的值后两位不要
var imageAddr = filePicker.attr("id").substring(0, divlen-2);
var genre=$(":input[name='genre']").val();
data=$.extend(data,{
genre:genre,
imageAddr:imageAddr
});
data.formData= {genre:genre,imageAddr:imageAddr}; });
}); });
删除图片只是隐藏div,不能删服务器
<script type="text/javascript">
/*删除图片 */
function deleteImage(path) {
//图片名称
var imageAddrs = mini.get(path).getValue();
alert(path);
alert(imageAddrs); mini.get(path).setValue("");
$("#"+path+"_1").attr("src"," ");
$("#"+path+"_5").hide();
document.getElementById(path + "_4").style.display = '';
document.getElementById(path + "_3").style.display = '';
/*
硬删除
if (imageAddrs == ""|| imageAddrs== null|| imageAddrs == undefined) {
alert("照片为空,请重新操作");
}else{ $.ajax({
type : "POST",
url : "ajax/removeImage",
data : {
imageAddr : imageAddrs
},
dataType : "json",
// 下面三个参数要指定,如果不指定,会报一个JQuery的错误
success : function(data) {
console.log(data);
console.log(data.mess);
alert(data.mess);
alert(imageAddrs);
// 删除成功后刷新页面
$(".cxuploder").html(page);
window.location.reload();
}
});
} */
}
</script>

上传控制层

    // 允许上传图片的格式
private static final String[] IMAGE_TYPE = { ".jpg", ".jpge", ".bmp", ".png", "gif" }; /**
*图片上传
*
* @param id
* @param name
* @param flog
* @param autoId
* @param size
* @param type
* @param file
* @param request
*/
@RequestMapping(value = "fileUpload.do",method = RequestMethod.POST)
@ResponseBody
public String fileUpload(String genre,String imageAddr,@RequestParam("file")MultipartFile file,HttpServletRequest request,HttpServletResponse response){ Map<String,Object> resultMap=new HashMap <String, Object>(); Boolean flag = false;
System.out.println(file.getOriginalFilename());
//校验图片格式
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
flag = true;
break;
}
}
//如果图片校验错误,直接返回。
if (!flag) {
return "";
} //获取当前时间 File.separator等同于/或者\\ String fileFolder = File.separator + DateUtil.getYear(new Date())
+ File.separator + DateUtil.getMonth(new Date()) + File.separator
+ DateUtil.getDay(new Date());
try {
//设置根目录
//设置根目录
/*String filePathGen = request.getSession().getServletContext()
.getRealPath("/") + "upload/photoPhoto/images/";
String uploadPath ="";*/
String uploadPath="";//图片上传的目录
InputStream in = this.getClass().getResourceAsStream("/conf.properties");
Properties props = new Properties();
InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8");
props.load(inputStreamReader);
if("renyuan".equals(genre)) {
uploadPath = props.getProperty("Upload_path")+genre+fileFolder;
}else if ("cheliang".equals(genre)) {
uploadPath =props.getProperty("Upload_path")+genre+fileFolder;
} System.out.println(file.getOriginalFilename()); //生成图片的绝对路径
//重新命名
String newFileName= "";
String fileName = file.getOriginalFilename();
if(null!=fileName){
newFileName=UUID.randomUUID ()+fileName.substring (fileName.lastIndexOf ("."));
}
//创建File对象
File newfile = new File(uploadPath+File.separator+newFileName);
//如果文件目录不存在,则进行创建
if (!newfile.isDirectory()) {
newfile.mkdirs();
}
//把图片写入到磁盘中
try {
file.transferTo(newfile);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} resultMap.put("fileAdress","/upload"+File.separator+genre+fileFolder+File.separator+newFileName);
resultMap.put("imageAddr",imageAddr);
resultMap.put("uploadFlag",true);
//获取照片类型 人员/车辆 System.out.println(genre);
System.out.println(imageAddr); } catch (Exception e) {
e.printStackTrace();
resultMap.put("uploadFlag",false);
}
String json=JSONObject.toJSONString(resultMap).toString();
writeJson(json,response); return null;
} /*
* 写入数据
*/
private void writeJson(String json, HttpServletResponse response) {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.print(json);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != out) {
out.close();
}
}
}

上面的是上传图片的控制层,点击上传图片立马上传