java 通用文件上传并保存图片 乔乐共享uploadfiledirectoryresource
程序员文章站
2022-05-17 11:33:47
...
/** * 通用图片上传 */ public void commonImgUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml; charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter pw = response.getWriter(); String xml = ""; String imgName = getParam(request, "imgName"); String imgValue = getParam(request, "imgValue"); String type = getParam(request, "type"); String encryptCode = getParam(request, "encryptCode"); log.debug("图片上传,图片名称:" + imgName + ",上传类型:" + type); if (MD5Checker.check(encryptCode, imgName)) { try { String path = this.getClass().getClassLoader().getResource("").getPath(); log.info("当前路径:" + path); path = path.replace("WEB-INF/classes/", "pictures/" + type + "/"); log.info("替换后路径:" + path); File temp = new File(path); if (!temp.isDirectory()) { log.info("创建目录path: " + path); temp.mkdirs(); } path += imgName; log.info("图片全path: " + path); FileUtil.saveFile(path, (new BASE64Decoder()).decodeBuffer(imgValue), "UTF-8"); xml = "success"; log.info("上传图片:" + path + "成功!"); } catch (Exception e) { log.info("上传图片失败," + e.getMessage()); xml = "fail"; } } else { xml = "<data><resultCode>" + "09" + "</resultCode>" + "<resultMsg>" + "摘要验证错误" + "</resultMsg>" + "</data>"; } pw.print(xml); if (null != pw) { pw.close(); } }