一、引用相关的css和js文件
<link rel="stylesheet" type="text/css" href="${TEMPLATE_BASE_PATH}/jmrp/webuploader-0.1.5/webuploader.css">
<script type="text/javascript" src="${TEMPLATE_BASE_PATH}/jmrp/webuploader-0.1.5/webuploader.js"></script>
二、相关的html
<dl class="data_header">
<dt id="divImg" style="border-radius:50%;overflow:hidden;"><img id="itemImg" style="width:82px;height:82px;" src='${httpPhotoPath?default("")}' οnerrοr="javascript:this.src='${TEMPLATE_BASE_PATH}/images/my_photo.png'"></dt>
<dt style="margin-top: 12px;"><span id="userName2">${userInfo.userName?default("")}</span><div id="filePicker" style="margin-top: 10px;" class="webuploader-container">修改头像</div></dt>
<dt><button id="btnUpload" οnclick="uploadImageOK();" style="display:none;">确定</button></dt>
<dd>注册时间:${userInfo.createTime?default("")}</dd>
</dl>
<input id="itemImgPath" type="hidden" value="${userInfo.photoPath?default("")}" />
<input type="hidden" id="userId" name="userId" value="${userInfo.userId}">
三、相应的js
<script type="text/javascript">
//清空
function clearItemInfo(){
el("itemImgPath").value = "";
$('#itemImg').attr( 'src', "" );
el('itemImgPath').value = "";
$( '#divImg' ).find('.info').remove();
$( '#divImg' ).find('.error').remove();
$("#btnUpload").css("display", "none");
}
var $ = jQuery,
uploader = WebUploader.create({
// 选完文件后,是否自动上传。
auto: true,
// 不压缩image
resize: false,
// swf文件路径
swf: '${TEMPLATE_BASE_PATH}/js/webuploader-0.1.5/Uploader.swf',
// 文件接收服务端。
server: BASE_PATH+'/uploadUserFace', //发送请求到web.xml
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#filePicker',
// 只允许选择图片文件。
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});
// 当有文件添加进来的时候
uploader.on( 'fileQueued', function( file ) {
clearItemInfo();
// 创建缩略图
// thumbnailWidth x thumbnailHeight 为 82 x 82
uploader.makeThumb( file, function( error, src ) {
if ( error ) {
$('#itemImg').replaceWith('<span>不能预览</span>');
return;
}
$('#itemImg').attr( 'src', src );
}, 82, 82 );
});
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
var $li = $( '#divImg'),
$info = $li.find('div.info');
// 避免重复创建
if ( !$info.length ) {
//$info = $('<div class="info"></div>').appendTo( $li );
}
//$info.text(Math.round(percentage * 100) + '%');
});
uploader.on( 'uploadSuccess', function( file, resporse) {
var $li = $( '#divImg'),
$info = $li.find('div.info');
// 避免重复创建
if ( !$info.length ) {
//$info = $('<div class="info"></div>').appendTo( $li );
}
//$info.text('上传成功');
$("#btnUpload").css("display", "block");
});
uploader.on( 'uploadError', function( file ) {
var $li = $( '#divImg'),
$error = $li.find('div.error');
// 避免重复创建
if ( !$error.length ) {
$error = $('<div class="error"></div>').appendTo( $li );
}
$error.text('上传失败');
});
uploader.on( 'uploadComplete', function( file ) {
$( '#divImg' ).find('.progress').remove();
});
uploader.on( 'uploadAccept', function( file, response ) {
if ( response._raw ) {
var result = JSON.parse(response._raw);
el("itemImgPath").value = result.filepath;
$('#itemImg').attr( 'src', result.httpfilepath );
return true;
}
// 通过return false来告诉组件,此文件上传有错。
return false;
});
//确认修改上传头像
function uploadImageOK(){
$.ajax({
url : '${BASE_PATH}' +'/userCenter/editUserPhoto.json',
type:"POST",
dataType : 'json',
data : {userId : $.trim($("#userId").val()),
photoPath: $.trim($("#itemImgPath").val())},
success : function(data){
if(data.result){
showSuccess('修改成功!');
$( '#divImg' ).find('.info').remove();
$( '#divImg' ).find('.error').remove();
$("#btnUpload").css("display", "none");
$('#myPhoto').attr( 'src', $('#itemImg').attr('src'));
}else{ //编辑失败
showError("修改失败,请重新修改");
}
}
});
}
</script>
四、发送请求到web.xml
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/uploadUserFace</url-pattern>
</servlet-mapping>
五、在UploadServlet中响应该请求
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
//ConfigService configService = (ConfigService) ApplicationUtils.getBean("configService");
String savePath = PropertyUtils.getValue("faceIconPath");
String savePathUrl = PropertyUtils.getValue("faceIconHttpPath");
String filePath = savePath;
filePath = filePath.endsWith("/") || filePath.endsWith("\\") ? filePath.replace("\\", "/") : filePath + "/";
filePath = filePath + "icon/";
File uploadFile = new File(filePath);// 上传文件目录
if (!uploadFile.exists())
{
uploadFile.mkdirs();
}
// 临时文件目录
File tempPathFile = new File(filePath + "imgTemp/");
if (!tempPathFile.exists())
{
tempPathFile.mkdirs();
}
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 得到所有的表单域,它们目前都被当作FileItem
List<FileItem> fileItems = upload.parseRequest(request);
String id = "";
String fileName = "";
String guid = "";
// 如果大于1说明是分片处理
int chunks = 1;
int chunk = 0;
FileItem tempFileItem = null;
for (FileItem fileItem : fileItems)
{
if (fileItem.getFieldName().equals("id"))
{
id = fileItem.getString();
}
else if (fileItem.getFieldName().equals("name"))
{
fileName = new String(fileItem.getString().getBytes("ISO-8859-1"), "UTF-8");
}
else if (fileItem.getFieldName().equals("chunks"))
{
chunks = NumberUtils.toInt(fileItem.getString());
}
else if (fileItem.getFieldName().equals("chunk"))
{
chunk = NumberUtils.toInt(fileItem.getString());
}
else if (fileItem.getFieldName().equals("file"))
{
tempFileItem = fileItem;
}
else if (fileItem.getFieldName().equals("guid"))
{
guid = fileItem.getString();
}
}
if (StringUtil.isNullOrEmpty(guid))
{
guid = UUID.randomUUID().toString();
}
String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
fileName = guid + "." + ext;
// 临时目录用来存放所有分片文件
String tempFileDir = filePath + "imgTemp" + File.separator + id + "_" + guid;
File parentFileDir = new File(tempFileDir);
if (!parentFileDir.exists())
{
parentFileDir.mkdirs();
}
logger.debug("处理文件:" + fileName + "_" + chunk + ".part,共 " + chunks + " 块");
// 分片处理时,前台会多次调用上传接口,每次都会上传文件的一部分到后台(默认每片为5M)
File tempPartFile = new File(parentFileDir, fileName + "_" + chunk + ".part");
FileUtils.copyInputStreamToFile(tempFileItem.getInputStream(), tempPartFile);
// 是否全部上传完成
// 所有分片都存在才说明整个文件上传完成
boolean uploadDone = true;
for (int i = 0; i < chunks; i++)
{
File partFile = new File(parentFileDir, fileName + "_" + i + ".part");
if (!partFile.exists())
{
uploadDone = false;
break;
}
}
// 所有分片文件都上传完成
// 将所有分片文件合并到一个文件中
if (uploadDone)
{
DateFormat df = new SimpleDateFormat("yyyy/MM/dd/");
String destFilePath = filePath + df.format(new Date()) + File.separator;
File destFileDir = new File(destFilePath);
if (!destFileDir.exists())
{
destFileDir.mkdirs();
}
File destTempFile = new File(destFilePath, fileName);
for (int i = 0; i < chunks; i++)
{
File partFile = new File(parentFileDir, fileName + "_" + i + ".part");
FileOutputStream destTempfos = new FileOutputStream(destTempFile, true);
try
{
FileUtils.copyFile(partFile, destTempfos);
}
catch (IOException ee)
{
logger.error(ee.getMessage(), ee);
}
finally
{
destTempfos.close();
}
}
// 得到 destTempFile 就是最终的文件
// 删除临时目录中的分片文件
try
{
FileUtils.deleteDirectory(parentFileDir);
}
catch (IOException ee)
{
logger.error(ee.getMessage(), ee);
}
// 删除临时文件
//destTempFile.delete();
Map<String, String> pathMap = new HashMap<String, String>();
destFilePath = destFilePath.replace("\\", "/");
pathMap.put("filepath", destFilePath + fileName);
savePath = savePath.replace("\\", "/");
savePathUrl = savePathUrl.replace("\\", "/");
destFilePath = destFilePath.replace(savePath, savePathUrl);
pathMap.put("httpfilepath", destFilePath + fileName);
//返回guid
response.getWriter().print(JSONObject.fromObject(pathMap).toString());
}
else
{
// 临时文件创建失败
if (chunk == chunks - 1)
{
//FileUtils.deleteDirectory(parentFileDir);
//ResponseUtil.responseFail(response, "500", "内部错误");
}
}
}
}
catch (Exception e)
{
logger.error(e.getMessage(), e);
//ResponseUtil.responseFail(response, "500", "内部错误");
}
}
六、上传图片成功