Cropper.js从前台到后台的完整实例应用

插件很完善,可惜API都是英文看不懂,折腾一天用原demo改出来,这里记下笔记。

先是html主体








	
Picture

ajax调用servlet

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取用户ID
		HttpSession session = request.getSession();
		String userid = (String) session.getAttribute("id");
		//收到AJAX的data
		String imagefile = request.getParameter("file");
		//执行图片上传方法,并获得头像图片地址		
		String path = uploadbiz.UploadHeadImage(userid, imagefile);		
		//更新session中的头像地址	
		session.setAttribute("headimageurl", path);		
	}

上传方法

package sin.service;
import java.io.FileOutputStream;
import sin.dao.UserInfoDao;
import sin.plugins.NewAFileName;
import sun.misc.BASE64Decoder;
@SuppressWarnings("restriction")
public class UploadHeadImageBiz {
	@SuppressWarnings("unused")
	public String UploadHeadImage(String userid, String imagefile) {
		NewAFileName newname = new NewAFileName();
		UserInfoDao userinfodao = new UserInfoDao();
		String path = null;		
        BASE64Decoder decoder = new BASE64Decoder();
        try {
        	//去掉头data:image/jpeg;base64,
        	String imagebasefile = imagefile.substring(23);
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imagebasefile);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            //生成JPEG图片输出流,名字,保存路径            
            String filename = userid + newname.getFileName();            
            path = "../../../../sin/upload/headimages/" + filename;
            FileOutputStream out = new FileOutputStream(path);
            //更新用户头像URL
            Boolean result = userinfodao.updateUserHeadImageById(userid, path);
            out.write(bytes);
            out.flush();
            out.close();
            } catch (Exception e) {
            }
        return path;
    }
}

附手机上使用的效果图

Cropper.js从前台到后台的完整实例应用_第1张图片

你可能感兴趣的:(Cropper.js从前台到后台的完整实例应用)