html代码
<input type="file" name="upload_org_code" id="upload_org_code"/>
<input type="hidden" name="upload_org_code_name" id="upload_org_code_name" />
<img style="display:none" id="upload_org_code_img" src="" width="50" height="50">
前端js代码:uploadfiy3.2
<link rel="Stylesheet" href="<%=basePath %>/static/css/uploadify.css" />
<script type="text/javascript" src="<%=basePath %>static/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="<%=basePath %>static/js/jquery.uploadify.min.js"></script>
var faceImg= $("#upload_org_code");var faceImgName=$("#upload_org_code_name");
faceImgCommon(faceImg,faceImgName,"face");
function faceImgCommon(btn,btnName,type){
btn.uploadify({
'height' : 20,
'width' : 50,
'buttonText' : '选择图片',
'swf' : '${pageContext.request.contextPath}/static/js/uploadify.swf',
'uploader' : '${pageContext.request.contextPath}/customerService/uploadFaceImg',
'auto' : true,
'multi' : false,
'removeCompleted':false,
//'cancelImg' : '${pageContext.request.contextPath}/js/uploadify/uploadify-cancel.png',
'fileTypeExts' : '*.jpg;*.jpge;*.gif;*.png',
'fileSizeLimit' : '2MB',
'onUploadSuccess':function(file,data,response){
alert('修改成功!');
var url=data+"?s="+ (new Date()).getTime();
if(type=='face'){
$('#upload_org_code-queue').hide();
$("#upload_org_code_img").attr("src",url);
$("#upload_org_code_img").show();
}else{
$('#upload_right_img-queue').hide();
$("#upload_right_img_img").attr("src",url);
$("#upload_right_img_img").show();
}
$('#' + file.id).find('.data').html('');
btnName.val(data);
},
//加上此句会重写onSelectError方法【需要重写的事件】
'overrideEvents': ['onSelectError', 'onDialogClose'],
'onClearQueue': function (queueItemCount) {
alert("取消上传");
return;
},
//返回一个错误,选择文件的时候触发
'onSelectError':function(file, errorCode, errorMsg){
switch(errorCode) {
case -110:
alert("文件 ["+file.name+"] 大小超出系统限制的" + jQuery(btn).uploadify('settings', 'fileSizeLimit') + "大小!");
break;
case -120:
alert("文件 ["+file.name+"] 大小异常!");
break;
case -130:
alert("文件 ["+file.name+"] 类型不正确!");
break;
}
},
'onUploadStart' : function(file) {//动态传值,只能在formData这样传
btn.uploadify("settings", "formData", { "serviceid" :serviceid,'type':type})
} ,
});
}
后台接收并将图片刷到页面显示:
@RequestMapping(value="/uploadFaceImg")
public void uploadFaceImg(HttpServletRequest request,HttpServletResponse response) throws IOException {
String ret_fileName = null;//返回给前端已修改的图片名称
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// 文件保存目录路径
//String savePath = "\\static\\faceimg\\";
String tempFileDir=request.getSession().getServletContext().getRealPath("/") + "static\\faceimg\\";
String vtempDir=request.getSession().getServletContext().getContextPath() +"/static/faceimg/";
// 临时文件目录
//String tempPath = "static\\faceimg\\";
File dirTempFile1 = new File(tempFileDir);
if (!dirTempFile1.exists()) {
dirTempFile1.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(20 * 1024 * 1024); // 设定使用内存超过5M时,将产生临时文件并存储于临时目录中。
factory.setRepository(new File(tempFileDir)); // 设定存储临时文件的目录。
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List<?> items = upload.parseRequest(request);
Iterator<?> itr = items.iterator();
String type="1";
String serviceid="1";
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
if("type".equals(item.getFieldName())){
type=item.getString();
}
if("serviceid".equals(item.getFieldName())){
serviceid=item.getString();
}
if(null!=fileName){
//取后缀
String suffix=fileName.substring(fileName.indexOf("."),fileName.length());
fileName=serviceid+"_"+type+suffix;
IUserInfo user=new IUserInfo();
user.setI_user_id(Long.parseLong(serviceid));
if(type.equals("face")){
user.setI_user_face(vtempDir+fileName);
}else {
user.setI_user_rightimg(vtempDir+fileName);
}
ret_fileName=vtempDir+fileName;
iUserService.updateUserInfo(user);
}
if (!item.isFormField()) {
try {
File uploadedFile = new File(tempFileDir,fileName);
OutputStream os = new FileOutputStream(uploadedFile);
InputStream is = item.getInputStream();
byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度
int length = 0;
while ((length = is.read(buf)) > 0) {
os.write(buf, 0, length);
}
// 关闭流
os.flush();
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
//将已修改的图片名称返回前端
out.print(ret_fileName);
out.flush();
out.close();
}