需求说明:

用户在上传头像的时候,选择自己的头像上传完毕,同时会进行截图,并把四个点的坐标传到后台进行截图。

功能点一:

上传文件,同时命名:

apache的fileupload组件上传。优点:可以同时上传多个文件,也可以同时上传文本域

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setHeader("Cache-Control", "no-cache");

response.setContentType("text/plain; charset=UTF-8");

request.setCharacterEncoding("utf-8");

SessionManager sessionManager = SessionManager.getInstance();

UserSession user = (UserSession) sessionManager.getSession(request);

long suberId = 0;

if(user!=null){

if(user.getSuber()!=null){

l.debug("session中suber No null");

suberId = user.getSuber().getSuberId();

}

}

// 文件上传部分

boolean isMultipart = ServletFileUpload.isMultipartContent(request);

String sourceName = null;// 源名

long size = 0L;// 大小

String fileName="";

String message = "上传成功!";// 返回信息

/**

* 上传文件的重命名

*/

String reName = "";

String suffix ="";

JSONObject jsonResult = new JSONObject();

if (isMultipart) {

try {

// 设置上传(缓存目录,编码方式,文件大小限制)

DiskFileItemFactory factory = new DiskFileItemFactory();

factory.setRepository(new File(XingbookConfig.icon_tempPath));

ServletFileUpload upload = new ServletFileUpload(factory);

upload.setHeaderEncoding("utf-8");

upload.setSizeMax(g.uploadSizeMax);

// 上传表单处理

List<FileItem> fileItems = upload.parseRequest(request);


Iterator<FileItem> iter = fileItems.iterator();

while (iter.hasNext()) {

FileItem item = iter.next();

if (item.isFormField()) {

} else {

// 获得填充实例

StringBuffer pathTemp = new StringBuffer();

sourceName = item.getName().trim();// 保持原名上传

suffix = sourceName.substring(sourceName.lastIndexOf('.') + 1).toLowerCase();// 后缀名

reName = suberId + ".jpg" ;// 重命名文件,当前用户的id+上传文件的后缀名

// 获得目标路径

pathTemp.delete(0, pathTemp.length());

pathTemp.append(XingbookConfig.icon_srcPath);

String iconPath = pathTemp.toString();

// 获得新名称完整路径地址

pathTemp.delete(0, pathTemp.length());

pathTemp.append(iconPath).append(sourceName);

FileOperations operation = new FileOperations();

//判断文件存在性,执行相应操作

//说明:文件的操作工具类,见《常用到的文件工具操作》

int result = operation.checkFileExists(pathTemp.toString());

if(result==2){

File fileOnServer = new File(iconPath, reName);

fileOnServer.delete();

}

Thread.sleep(1000);//留出时间往磁盘写数据流

File fileOnServer = new File(iconPath, reName);

item.write(fileOnServer);

size = fileOnServer.length();

fileName = String.valueOf(suberId);

}

}

} catch (Exception e) {

message = "上传过程中遇到问题,请联系管理员 !";

l.error(e.getMessage());

e.printStackTrace();

}

} else {

message = "上传过程中遇到问题,请联系管理员";

}


try {

jsonResult.put("result", message);

jsonResult.put("fileName", fileName);

} catch (JSONException e) {

l.warn(e.getMessage());

}


PrintWriter out = response.getWriter();

out.print(jsonResult.toString());

}

功能点二:截图:


public class IconAction extends BaseAction {

private int x;// X点坐标

private int y;// Y点坐标

private int w;// 宽度

private int h;// 高度


@Override

public String execute() throws Exception {

String suffix = ".jpg";

String _suffix = "";

long uid = sess.getSuber().getSuberId();

String srcPath = XingbookConfig.icon_srcPath + uid + suffix;

String targetPath = XingbookConfig.icon_targetPath + uid + suffix;

File file = new File(srcPath);

if(file.exists()){

_suffix = getFormatInFile(file);//文件上传之后,将文件格式改为jpg格式,但是文件的读取原格式仍为png,所以需要获得文件的原文件格式

}

boolean result = cutImage(x, y, w, h, _suffix, srcPath, targetPath);

if (result) {

succe***esponse(null);

} else {

setMessage(R.ResultCode.USER_ICON_CUT, R.ResultCode.USER_ICON_CUT_MSG);

}

return MESSAGE;

}


@Override

public boolean needLogin() {

return true;

}


/**

* 图片截取

* <p>

* Title: cutImage

* </p>

* <p>

* Description:

* </p>

*

* @param x

*            截点横坐标

* @param y

*            截点纵坐标

* @param w

*            长度

* @param h

*            宽度

* @param suffix

*            后缀名

* @param srcPath

*            截图的原始路径

* @param targetPath

*            截图的目标路径

* @return 是否截图成功

*/

public boolean cutImage(int x, int y, int w, int h, String suffix, String srcPath, String targetPath) {

FileInputStream is = null;

ImageInputStream iis = null;

boolean result = false;

try {

is = new FileInputStream(srcPath);

Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(suffix);

ImageReader reader = it.next();

iis = ImageIO.createImageInputStream(is);

reader.setInput(iis, true);

ImageReadParam param = reader.getDefaultReadParam();

Rectangle rect = new Rectangle(x, y, w, h);

param.setSourceRegion(rect);

BufferedImage bi = reader.read(0, param);

ImageIO.write(bi, suffix, new File(targetPath));

result = true;

} catch (Exception e) {

e.printStackTrace();

} finally {

if (is != null) {

try {

is.close();

} catch (IOException e) {

l.debug("is关闭的时候出现异常");

}

}

if (iis != null) {

try {

iis.close();

} catch (IOException e) {

l.debug("iis关闭的时候出现异常");

}

}

}

return result;


}

/**

* 在上传文件时,修改文件的格式为jpg,但是需要获得文件的真实格式。

* @param f

* @return

*/

public static String getFormatInFile(File f){

return getFormatName(f);

}


private static String getFormatName(Object o) {

ImageInputStream iis;

try {

iis = ImageIO.createImageInputStream(o);

Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);

if(!iter.hasNext()){

return null;

}

ImageReader reader = iter.next();

iis.close();

return reader.getFormatName();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}


public int getX() {

return x;

}


public void setX(int x) {

this.x = x;

}


public int getY() {

return y;

}


public void setY(int y) {

this.y = y;

}


public int getW() {

return w;

}


public void setW(int w) {

this.w = w;

}


public int getH() {

return h;

}


public void setH(int h) {

this.h = h;

}