新学习了Jquery的uploadify插件,异步上传图片,功能还是非常强大的。
这里说一下使用步骤,后台是servlet接收的。
引入包
jsp中引进
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/js/uploadify.css">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.uploadify.min.js"></script>
servlet中引入两个jar包
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
jsp中代码如下
<script type="text/javascript">
$(function () {
$("#uploadPic").uploadify({
// 'debug' : true, //开启调试
'auto' : true, //是否自动上传
'swf' : '<%=request.getContextPath()%>/js/uploadify.swf?var='+(new Date()).getTime(),
'uploader' : '<%=request.getContextPath()%>/upload',
'queueID' : 'fileQueue',//队列id,用来展示上传进度的
'width' : '75', //按钮宽度
'height' : '24', //按钮高度
'queueSizeLimit' : 1, //同时上传文件的个数
'fileTypeDesc' : '视频文件', //可选择文件类型说明
'fileTypeExts' : '*.png; *.jpg; *.jpeg; *.gif', //控制可上传文件的扩展名
'multi' : true, //允许多文件上传
'buttonText' : '选择图片',//按钮上的文字
'fileSizeLimit' : '2MB', //设置单个文件大小限制
'fileObjName' : 'pic', //<input type="file"/>的name
'method' : 'post',
'removeCompleted' : true,//上传完成后自动删除队列
'onFallback' :function(){
alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
},
'onUploadSuccess' : function(file, data, response){//单个文件上传成功触发
$("#showImgId").attr('src', data);
$("#pic_id").val(data);//data就是action中返回来的数据
},'onQueueComplete' : function(){//所有文件上传完成
// alert("文件上传成功!");
}
});
});
</script>
</head>
<body>
<form action="${pageContext.request.contextPath }/test" method="post">
<div id="upload_pic111">
<input type="file" id="uploadPic" name="pic">
<div id="fileQueue"></div>
<img src="" id = "showImgId" style="width:200px;height:100px;" >
</div>
<input type="hidden" id="pic_id" name="pic" value="">
</br>
<input type="submit" value="提交">
</form>
</body>
servlet后台代码如下
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//为解析类提供配置信息
DiskFileItemFactory factory = new DiskFileItemFactory();
//创建解析类的实例
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> fileItem = null;
try {
fileItem = fileUpload.parseRequest(request);
} catch (Exception e) {
e.printStackTrace();
}
//解析
Iterator<FileItem> iterator = fileItem.iterator();
String picName = null;
while(iterator.hasNext()){
FileItem item = iterator.next();
if(!item.isFormField()){//不是表单域
//获取文件name 'fileObjName': 'pic',
String name = item.getFieldName();
//获取图片名
picName = item.getName();
String type = item.getContentType();
File file = new File("D:/upload/" + picName);
try {
item.write(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
response.getWriter().print("/" + picName);
}
ok了 , 还是非常简单的。