public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); ServletContext context = getServletContext(); String filepath = context.getRealPath("images") + "\\tLogo\\"; String url = "/Front_End/front_end_prompt.jsp"; // TeamDAO tDAO = null; try { LogoUpload tlogo = new LogoUpload(); // tDAO = DAOFactory.getTeamDAOInstance(); if (tlogo.update(request, context, filepath)) { // tDAO. url = "/Front_End/Team_Apply/team_regist_success.jsp"; } else { url = url + "?e=920"; } } catch (FileUploadException e) { e.printStackTrace(); url = url + "?e=921"; } catch (Exception e) { e.printStackTrace(); url = url + "?e=920"; } finally { request.getRequestDispatcher(url).forward(request, response); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(factory); // 设置上传文件大小的上限,-1表示无上限 fileUpload.setSizeMax(-1); // 上传文件,解析表单中包含的文件字段和普通字段 try { List<FileItem> items = fileUpload.parseRequest(request); if (items.size() > 0) { FileItem item = (FileItem) items.get(0); String name = item.getName(); String path = getServletContext().getRealPath(Constants.UPLOAD_IMG_PATH) + "/" + name; logger.info("上传用户图片信息,图片名:" + name + ";上传路径:" + path); // 实现图片上传 try { item.write(new File(path)); // 就用户头像路径保存. User user = new User(); user.setPhone(request.getHeader("owner")); user.setImgPath(Constants.UPLOAD_IMG_PATH + "/" + name); userService.saveOrUpdateUserInfo(user); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * @param request * @throws UnsupportedEncodingException */ public void parseRequest(HttpServletRequest request) throws UnsupportedEncodingException { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(sizeThreshold); if (repository != null) factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { String fieldName = item.getFieldName(); String value = item.getString(encoding); parameters.put(fieldName, value); } else { if (!super.isValidFile(item)) { continue; } if (fileItem == null) fileItem = item; } } } catch (FileUploadException e) { e.printStackTrace(); } }
@RequestMapping(value = "/UploadFile.htm") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); File file = null; try { List<FileItem> items = upload.parseRequest(request); if (isMultipart) { for (FileItem item : items) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); file = new File(request.getRealPath(File.separator) + File.separator + name); item.write(file); } } readFileImpl.readCSVFile(file); request.getRequestDispatcher("jsp/display.jsp").forward(request, response); } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Fachada fachada = Fachada.obterInstancia(); String acao = ""; List<FileItem> items = null; if (ServletFileUpload.isMultipartContent(request)) { try { items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); } catch (FileUploadException e1) { e1.printStackTrace(); } for (FileItem item : items) { if (item.getFieldName().equals("acao")) { acao = item.getString(); } } } else { acao = request.getParameter("acao"); } try { if (acao.equals("deletar")) { deletarMembro(request, fachada); } else { cadastrarEditarMembro(request, response, fachada, acao, items); } request.getRequestDispatcher("sucesso.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); request.getRequestDispatcher("falha.jsp").forward(request, response); } }
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); FileItemIterator iterator = null; try { iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.getFieldName().equals("bundleUpload")) { String fname = item.getName(); if (!fname.endsWith(".jar")) { Logger.warn(this, "Cannot deplpy bundle as it is not a JAR"); writeError(response, "Cannot deplpy bundle as it is not a JAR"); break; } File to = new File(Config.CONTEXT.getRealPath("/WEB-INF/felix/load/" + fname)); FileOutputStream out = new FileOutputStream(to); IOUtils.copyLarge(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } } } catch (FileUploadException e) { Logger.error(OSGIBaseAJAX.class, e.getMessage(), e); throw new IOException(e.getMessage(), e); } }
private FileItem fetchFileFromRequest(HttpServletRequest request, String imageFieldName) { try { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { String fieldname = item.getFieldName(); if (fieldname.equals(imageFieldName)) { return item; } } } } catch (FileUploadException e) { e.printStackTrace(); } try { throw new CkFileManagerPropertyException( String.format( "Field name %s was not found in the request. " + "Are you sure this is the correct image field name?", imageFieldName)); } catch (CkFileManagerPropertyException e) { e.printStackTrace(); } return null; }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doPost(request, response); try { if (!ServletFileUpload.isMultipartContent(request)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } ServletFileUpload sfU = new ServletFileUpload(); FileItemIterator items = sfU.getItemIterator(request); while (items.hasNext()) { FileItemStream item = items.next(); if (!item.isFormField()) { InputStream stream = item.openStream(); Document doc = editor.toDocument(stream); stream.close(); handleDocument(request, response, doc); return; } } response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No XML uploaded"); } catch (FileUploadException fuE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, fuE.getMessage()); } catch (JDOMException jE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, jE.getMessage()); } }
@SuppressWarnings("unchecked") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("upload start------"); request.setCharacterEncoding("UTF-8"); StringBuffer savePath = new StringBuffer("/mnt/web/static/images/album/"); Calendar c = Calendar.getInstance(); DateFormat df = new SimpleDateFormat("yyyy/MM/dd/"); String date = df.format(c.getTime()); savePath.append(date); File dir = new File(savePath.toString()); if (!dir.exists()) { dir.mkdirs(); } DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("UTF-8"); List<FileItem> list = null; try { list = upload.parseRequest(request); } catch (FileUploadException e) { log.error(e.getMessage(), e); return; } log.info("file size:{}", list.size()); for (FileItem it : list) { if (!it.isFormField()) { String name = it.getName(); long size = it.getSize(); String type = it.getContentType(); log.info("name:{},size:{},type:{}", name, size, type); if (StringUtils.isBlank(name)) { continue; } String extName = null; if (name.lastIndexOf(".") >= 0) { extName = name.substring(name.lastIndexOf(".")); } File file = null; do { name = UUIDUtil.getRandomUUID(); file = new File(savePath + name + extName); } while (file.exists()); File saveFile = new File(savePath + name + extName); log.info("path:{}", saveFile.getAbsolutePath()); try { it.write(saveFile); albumService.newPhoto(1, saveFile.getAbsolutePath(), "none"); } catch (Exception e) { e.printStackTrace(); } } } response.getWriter().write("1"); log.info("upload end------"); }
public void doGet(HttpServletRequest request, HttpServletResponse response) { try { handle(request, response); } catch (IOException e) { e.printStackTrace(); } catch (FileUploadException e) { e.printStackTrace(); } }
/** * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's * multipart classes (see class description). * * @param saveDir the directory to save off the file * @param request the request containing the multipart * @throws java.io.IOException is thrown if encoding fails. */ public void parse(HttpServletRequest request, String saveDir) throws IOException { try { processUpload(request, saveDir); } catch (FileUploadException e) { if (LOG.isWarnEnabled()) { LOG.warn("Unable to parse request", e); } errors.add(e.getMessage()); } }
public boolean execute(HttpServletRequest request, HttpServletResponse response) throws CarbonException, IOException { try { return super.executeCommon(request, response); } catch (FileUploadException e) { e.printStackTrace(); // Todo: change body of catch statement use File | Settings | File // Templates. } return false; }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { System.out.println( "Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out.println( "File field " + name + " with file name " + item.getName() + " detected."); // Process the input stream int read = 0; final byte[] bytes = new byte[1024]; FileOutputStream fileOut = new FileOutputStream(new File(item.getName())); while ((read = stream.read(bytes)) != -1) { System.out.println("read " + read + " bytes"); fileOut.write(bytes, 0, read); } stream.close(); fileOut.close(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } // final Part filePart = req.getPart("file"); // int read = 0; // final byte[] bytes = new byte[1024]; // InputStream filecontent = filePart.getInputStream(); // final String fileName = getFileName(filePart); // FileOutputStream fileOut = new FileOutputStream(new File(fileName)); // while ((read = filecontent.read(bytes)) != -1) { // System.out.println("read " + read + " bytes"); // fileOut.write(bytes, 0, read); // } // filecontent.close(); // fileOut.close(); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (ServletFileUpload.isMultipartContent(request)) { UploadTools uploadTools = new UploadTools(); String path = request.getSession().getServletContext().getRealPath("/") + "/"; ServletFileUpload upload = uploadTools.initUpload(path); String image = null, introduce = null, strategy = null; try { List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if ("introduce".equals(item.getFieldName())) { introduce = item.getString(request.getCharacterEncoding()); } else if ("strategy".equals(item.getFieldName())) { strategy = item.getString(request.getCharacterEncoding()); } else { image = uploadTools.uploadFile(path, item); System.out.println(image); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } HttpSession session = request.getSession(true); Object cityName = session.getAttribute("searchcity"); // System.out.println(cityName); // Object image1 = session.getAttribute("image"); DBTools dbtools = new DBTools(); String sql = "update city set c_introduce='" + introduce + "',c_path='" + image + "',c_strategy='" + strategy + "' where c_name='" + cityName + "';"; int count = dbtools.update(sql); if (count > 0) { response.sendRedirect("success.jsp"); } } }
/** * The doPost method of the servlet. <br> * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); // InputStream is = request.getInputStream(); // InputStreamReader isr = new InputStreamReader(is); // char[] c = new char[100]; // while(isr.read(c)!=-1){ // System.out.println(c); // } String path = request.getRealPath("/"); String savePath = path + "file\\"; String tempPath = path + "temp\\"; File f = new File(tempPath); // byte[] b = new byte[1]; // int len = 0; // while((len=is.read(b))!=-1){ // fos.write(b,0,len); // } // fos.flush(); // fos.close(); // is.close(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(f); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1024 * 1024 * 1024); List<FileItem> items = new ArrayList<FileItem>(); try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } for (FileItem fileItem : items) { System.out.println(fileItem.getName()); System.out.println(fileItem.getFieldName()); System.out.println(fileItem.getSize()); InputStream is = fileItem.getInputStream(); FileOutputStream fos = new FileOutputStream(savePath + fileItem.getName()); byte[] b = new byte[1024]; int len = 0; while ((len = is.read(b)) != -1) { fos.write(b, 0, len); } fos.flush(); fos.close(); is.close(); } }
@POST @Path("{type:user|group}/{userid}") public Response doUpdateAuthorizable( @Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam(value = "type") String authorizableType, @PathParam(value = "userid") String authorizableId) { try { AuthorizableManager authorizableManager = getAuthorizableManager(request, response); Authorizable authorizable = authorizableManager.findAuthorizable(authorizableId); Response checkType = checkType(authorizable, authorizableType); if (checkType != null) { return checkType; } // process the post request. AuthorizableHelper authorizableHelper = new AuthorizableHelper(authorizableManager); ModificationRequest modificationRequest = new ModificationRequest(); modificationRequest.processRequest(request); authorizableHelper.applyProperties(authorizable, modificationRequest); authorizableHelper.save(); final List<String> feedback = modificationRequest.getFeedback(); return Response.ok( new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { ResponseUtils.writeFeedback(feedback, output); } }) .type(MediaType.APPLICATION_JSON_TYPE.toString() + "; charset=utf-8") .lastModified(new Date()) .build(); } catch (StorageClientException e) { return ResponseUtils.getResponse( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (AccessDeniedException e) { return ResponseUtils.getResponse(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); } catch (IOException e) { return ResponseUtils.getResponse( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (FileUploadException e) { return ResponseUtils.getResponse( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
private String getFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 如果是文件上传类型 StringBuffer fileStr = new StringBuffer(); // PrintWriter out = resp.getWriter(); if (ServletFileUpload.isMultipartContent(req)) { // 得到文件上传工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(5000 * 1024); factory.setRepository(new File("c:/temp")); // 处理文件上传核心类 ServletFileUpload fileUpload = new ServletFileUpload(factory); fileUpload.setFileSizeMax(50000 * 1024); // 设置文件上传类的编码格式 fileUpload.setHeaderEncoding("UTF-8"); // 集合数据 : FileItem对象 注意: 每一个表单域 对应一个 FileItem对象(封装) try { List<FileItem> fileItemList = fileUpload.parseRequest(req); for (FileItem item : fileItemList) { // 如果这个文本域是文件类型的 if (!item.isFormField()) { CustomLog.info(item.getFieldName()); InputStream inputStream = item.getInputStream(); BufferedInputStream bis = new BufferedInputStream(inputStream); int tempbyte; while ((tempbyte = bis.read()) != -1) { char c = (char) tempbyte; System.out.write(tempbyte); fileStr.append(c); } } else { // CustomLog.info(item.getFieldName()); // CustomLog.info(item.getString()); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return fileStr.toString(); }
@Override public void processAction(ActionRequest request, ActionResponse response) throws IOException, PortletException { ActionRequest myRequest = request; if (FileUploadUtil.isMultipart(request)) { // logger.info("multipart!"); try { myRequest = new FileUploadActionRequestWrapper(request); } catch (FileUploadException e) { logger.error(e.getMessage()); } } super.processAction(myRequest, response); }
@POST @Path("port") @Consumes(MediaType.MULTIPART_FORM_DATA) public void importData(@Context HttpServletRequest request) throws IcatException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new IcatException(IcatExceptionType.BAD_PARAMETER, "Multipart content expected"); } ServletFileUpload upload = new ServletFileUpload(); String jsonString = null; String name = null; // Parse the request try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); if (fieldName.equals("json")) { jsonString = value; } else { throw new IcatException( IcatExceptionType.BAD_PARAMETER, "Form field " + fieldName + "is not recognised"); } } else { if (name == null) { name = item.getName(); } porter.importData(jsonString, stream, manager, userTransaction); } } } catch (FileUploadException e) { throw new IcatException(IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage()); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imageString = ""; String imageDivId = ""; String focusURLDivId = ""; String normalURLDivId = ""; String imageWidthDivId = ""; String imageHeightDivId = ""; String imageLocX = ""; String imageLocY = ""; String newImageUpdateJSON = ""; String imageWidgetSavePath = (String) request.getSession().getAttribute("imageWidgetSavePath"); String fileName = ""; request.getParameter("inputImageFile"); String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory dfif = new DiskFileItemFactory(); dfif.setSizeThreshold(maximumfilesize); File outputDir = new File(imageWidgetSavePath); if (!outputDir.exists()) { outputDir.mkdirs(); } dfif.setRepository(new File("C:/data/")); ServletFileUpload upload = new ServletFileUpload(dfif); upload.setSizeMax(maximumfilesize); List<FileItem> fileItem = null; try { fileItem = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator<FileItem> i = fileItem.iterator(); try { File file; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { if (fi.getFieldName().equals("imageDivId")) { imageDivId = fi.getString(); } if (fi.getFieldName().equals("focusURLDivId")) { focusURLDivId = fi.getString(); } if (fi.getFieldName().equals("normalURLDivId")) { normalURLDivId = fi.getString(); } if (fi.getFieldName().equals("imageWidthDivId")) { imageWidthDivId = fi.getString(); } if (fi.getFieldName().equals("imageHeightDivId")) { imageHeightDivId = fi.getString(); } if (fi.getFieldName().equals("newImageUpdateJSON")) { newImageUpdateJSON = fi.getString(); } if (fi.getFieldName().equals("imageLocX")) { imageLocX = fi.getString(); } if (fi.getFieldName().equals("imageLocY")) { imageLocY = fi.getString(); } } if (!fi.isFormField()) { fileName = fi.getName(); if (fileName.lastIndexOf("\\") >= 0) { file = new File(imageWidgetSavePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File( imageWidgetSavePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); fileName = imageWidgetSavePath + fileName; File f = new File(fileName); BufferedImage bi = ImageIO.read(f); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, "png", baos); BASE64Encoder encoder = new BASE64Encoder(); imageString = encoder.encode(baos.toByteArray()); imageString = imageString.replaceAll("[\\t\\n\\r]+", " "); baos.close(); } } } catch (Exception ex) { System.out.println(ex); } } request.setAttribute("imageDivId", imageDivId); request.setAttribute("focusURLDivId", focusURLDivId); request.setAttribute("normalURLDivId", normalURLDivId); request.setAttribute("imageWidthDivId", imageWidthDivId); request.setAttribute("imageHeightDivId", imageHeightDivId); request.setAttribute("imageLocX", imageLocX); request.setAttribute("imageLocY", imageLocY); request.setAttribute("imageString", imageString); request.setAttribute("newImageUpdateJSON", newImageUpdateJSON); request.getRequestDispatcher("/index.jsp").forward(request, response); }
void onUploadException(FileUploadException ex) { message = "Upload exception: " + ex.getMessage(); ajaxResponseRenderer.addRender("uploadResult", uploadResult); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 转发处理 StringBuffer json = new StringBuffer(); String methodCall = req.getParameter("methodCall"); if (methodCall.equals("getResultDetailByBatchNo")) { // 通过原来的批量退款批次号获取退款详情 if (req.getParameter("batchNo") == null) { json.append("{success:false,msg:'参数[原批量退款批次号]不能为空'}"); } else { Map resultDetails = refundFastpayService.getResultDetailByBatchNo(req.getParameter("batchNo")); if (CollectionUtils.isEmpty(resultDetails)) { json.append( "{success:false,msg:'原批量退款批次号为:" + req.getParameter("batchNo") + "的批量退款信息不存在'}"); } else { json.append("{success:true,data:{"); json.append("batchNo:'" + resultDetails.get("batchNo") + "',"); json.append("batchNum:'" + resultDetails.get("batchNum") + "',"); json.append("batchData:'" + resultDetails.get("batchData") + "',"); json.append( "refundDate:'" + DateUtil.formatDate( (Date) resultDetails.get("refundDate"), "yyyy-MM-dd HH:mm:ss") + "',"); json.append("isSuccess:'" + resultDetails.get("isSuccess") + "',"); json.append( "successNum:'" + (resultDetails.get("successNum") != null ? resultDetails.get("successNum") : "") + "',"); json.append( "resultDetails:'" + (resultDetails.get("resultDetails") != null ? resultDetails.get("resultDetails") : "") + "',"); json.append( "relation:'" + (resultDetails.get("relation") != null ? resultDetails.get("relation") : "") + "',"); json.append( "totalRefund:'" + (resultDetails.get("totalRefund") != null ? resultDetails.get("totalRefund") : "") + "'"); json.append("},msg:'获取原批量退款批次号为:" + req.getParameter("batchNo") + "的批量退款信息成功!'}"); } } resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(json.toString()); resp.getWriter().close(); return; } else if (methodCall.equals("batchRefundImport")) { // 批量退款导入 // 解析文件 String realPath = null; String filePath = null; Result result = null; try { DiskFileItemFactory factory = new DiskFileItemFactory(); boolean isMutipart = ServletFileUpload.isMultipartContent(req); if (isMutipart) { ServletFileUpload upload = new ServletFileUpload(factory); List fileItems = upload.parseRequest(req); Iterator iterator = fileItems.iterator(); while (iterator.hasNext()) { FileItem fi = (FileItem) iterator.next(); if (!fi.isFormField()) { String fileName = fi.getName(); if (fileName == null || "".equals(fileName)) break; String suffix = fileName.substring(fileName.lastIndexOf(".")); String systemFileName = "upload-" + System.currentTimeMillis() + suffix; filePath = PropertiesUtil.getProperties("fileUploadPath", "D:/data/upload/") + systemFileName; // realPath = req.getSession().getServletContext().getRealPath("/") + filePath; realPath = filePath; try { File uploadedFile = new File(realPath); fi.write(uploadedFile); result = processRefundFastpayExcel(realPath); if (!result.isSuccess()) { // 失败 RequestDispatcher rd = req.getRequestDispatcher("/refund/result.jsp"); req.setAttribute("result", result); rd.forward(req, resp); } else { // 成功 req.getSession(true).setAttribute("result", result); resp.sendRedirect(req.getContextPath() + "/refund/success.jsp"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (methodCall.equals("batchRefundApply")) { // 批量退款申请 // 解析文件 String realPath = null; String filePath = null; Result result = null; String applyUser = null; String applyRemark = null; try { DiskFileItemFactory factory = new DiskFileItemFactory(); boolean isMutipart = ServletFileUpload.isMultipartContent(req); if (isMutipart) { ServletFileUpload upload = new ServletFileUpload(factory); List fileItems = upload.parseRequest(req); Iterator iterator = fileItems.iterator(); while (iterator.hasNext()) { FileItem fi = (FileItem) iterator.next(); if (!fi.isFormField()) { String fileName = fi.getName(); if (fileName == null || "".equals(fileName)) break; String suffix = fileName.substring(fileName.lastIndexOf(".")); String systemFileName = "upload-" + System.currentTimeMillis() + suffix; filePath = PropertiesUtil.getProperties("fileUploadPath", "D:/data/upload/") + systemFileName; // realPath = req.getSession().getServletContext().getRealPath("/") + filePath; realPath = filePath; File uploadedFile = new File(realPath); fi.write(uploadedFile); } else { String name = fi.getFieldName(); String value = fi.getString(); // 在enctype="multipart/form-data") 情况下,form表单的数据通过流传递,且在Tomcat服务器下,默认使用ISO-8859-1编码 value = new String(value.getBytes("ISO-8859-1"), "UTF-8"); if (name.equals("applyUser")) { applyUser = value; } if (name.equals("applyRemark")) { applyRemark = value; } } } try { // 简单校验,提交申请applyId为null result = processRefundFastpayApplyExcel(realPath, true, null, applyUser, applyRemark); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (FileUploadException e) { result.setMsg("附件上传失败导致申请失败!"); } catch (Exception e) { result.setMsg("服务器端异常导致申请失败!"); } if (!result.isSuccess()) { // 失败 RequestDispatcher rd = req.getRequestDispatcher("/refund/result.jsp"); req.setAttribute("result", result); rd.forward(req, resp); } else { // 成功 req.getSession(true).setAttribute("result", result); resp.sendRedirect(req.getContextPath() + "/refund/success.jsp"); } } else if (methodCall.equals("searchRefundFastpayApplyList")) { // 查询申请列表 int currentPage = Integer.valueOf(req.getParameter("currentPage").toString()); int startRecord = currentPage == 1 ? 0 : ((currentPage - 1) * Integer.valueOf(req.getParameter("pageSize").toString())); int totalPage = 0; if (req.getParameter("flag").toString().equals("0")) { startRecord = 0; } Map resultDetails = refundFastpayService.searchRefundFastpayApplyList( req.getParameter("startDate").toString(), req.getParameter("endDate").toString(), Integer.valueOf(req.getParameter("applyStatus").toString()), req.getParameter("applyUser").toString(), Boolean.valueOf(req.getParameter("isSignUser")), startRecord, Integer.valueOf(req.getParameter("pageSize").toString())); for (Map map : ((List<Map>) resultDetails.get("data"))) { json.append("{'id':'"); json.append(map.get("id")).append("','applyNo':'"); json.append(map.get("applyNo")).append("','batchNo':'"); json.append(map.get("batchNo")).append("','filepath':'"); json.append(map.get("filepath")).append("','applyStatus':'"); json.append(map.get("applyStatus")).append("','applyUser':'******','applyTime':'"); json.append(map.get("applyTime")).append("','applyRemark':'"); json.append(map.get("applyRemark")).append("','auditUser':'******','auditTime':'"); json.append(map.get("auditTime")).append("','auditRemark':'"); json.append(map.get("auditRemark")).append("','importUser':'******','importTime':'"); json.append(map.get("importTime")).append("','importRemark':'"); json.append(map.get("importRemark")).append("'"); json.append("},"); } if (json.toString().endsWith(",")) { json = new StringBuffer(json.substring(0, json.length() - 1)); } totalPage = (Integer.valueOf(resultDetails.get("rowCount").toString()) == 0 ? 1 : (Integer.valueOf(resultDetails.get("rowCount").toString()) + Integer.valueOf(req.getParameter("pageSize").toString()) - 1) / Integer.valueOf(req.getParameter("pageSize").toString())); json = new StringBuffer( "{success: true,rowCount:'" + resultDetails.get("rowCount") + "',data:[" + json + "],currentPage:'" + currentPage + "',totalPage:'" + totalPage + "'}"); resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(json.toString()); resp.getWriter().close(); return; } else if (methodCall.equals("auditRefundFastpayApply")) { // 审批 Result result = null; result = refundFastpayService.auditRefundFastpay( req.getParameter("applyId"), req.getParameter("auditUser"), // new String(req.getParameter("auditRemark").getBytes("iso-8859-1"), "UTF-8"), // req.getParameter("auditRemark"), HttpUtil.ConverUnicode(req.getParameter("auditRemark")), // reuncode Integer.valueOf(req.getParameter("applyStatus").toLowerCase())); if (result.isSuccess()) { json.append("{success:true}"); } else { json.append("{success:false, msg:'" + result.getMsg() + "'}"); } resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(json.toString()); resp.getWriter().close(); return; } else if (methodCall.equals("importRefundFastpayApply")) { // 导入 Result result = null; // 简单校验,提交申请applyId为null result = processRefundFastpayApplyExcel( null, false, req.getParameter("applyId"), req.getParameter("importUser"), // req.getParameter("importRemark") HttpUtil.ConverUnicode(req.getParameter("importRemark"))); if (result.isSuccess()) { json.append("{success:true}"); } else { json.append("{success:false, msg:'" + result.getMsg() + "'}"); } resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(json.toString()); resp.getWriter().close(); return; } else if (methodCall.equals("downloadFile")) { // 下载 Map map = refundFastpayService.getApplyDetailByBatchNo(req.getParameter("applyId")); String filePath = map.get("filepath").toString(); File dbFile = new File(filePath); FileInputStream fileIn = null; fileIn = new FileInputStream(dbFile); String contentType; contentType = "application/x-xls"; resp.setContentType(contentType); resp.setHeader( "Content-Disposition", "filename=" + filePath.substring(filePath.indexOf("upload-"))); byte[] buffer = new byte[1024 * 512]; while (true) { int bytes = fileIn.read(buffer); if (bytes == -1) { break; } resp.getOutputStream().write(buffer, 0, bytes); } resp.getOutputStream().flush(); resp.getOutputStream().close(); fileIn.close(); return; } /*else if(methodCall.equals("test")){ test(); }*/ }
/** * Process the blog entries * * @param httpServletRequest Request * @param httpServletResponse Response * @param user {@link org.blojsom.blog.BlogUser} instance * @param context Context * @param entries Blog entries retrieved for the particular request * @return Modified set of blog entries * @throws BlojsomPluginException If there is an error processing the blog entries */ public BlogEntry[] process( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlogUser user, Map context, BlogEntry[] entries) throws BlojsomPluginException { if (!authenticateUser(httpServletRequest, httpServletResponse, context, user)) { httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_LOGIN_PAGE); return entries; } String username = getUsernameFromSession(httpServletRequest, user.getBlog()); if (!checkPermission(user, null, username, FILE_UPLOAD_PERMISSION)) { httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE); addOperationResultMessage(context, "You are not allowed to upload files"); return entries; } File resourceDirectory = new File( _blojsomConfiguration.getInstallationDirectory() + _resourcesDirectory + user.getId() + "/"); String action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest); if (BlojsomUtils.checkNullOrBlank(action)) { _logger.debug("User did not request edit action"); httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE); } else if (PAGE_ACTION.equals(action)) { _logger.debug("User requested file upload page"); httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE); } else if (UPLOAD_FILE_ACTION.equals(action)) { _logger.debug("User requested file upload action"); // Create a new disk file upload and set its parameters DiskFileUpload diskFileUpload = new DiskFileUpload(); diskFileUpload.setRepositoryPath(_temporaryDirectory); diskFileUpload.setSizeThreshold(_maximumMemorySize); diskFileUpload.setSizeMax(_maximumUploadSize); try { List items = diskFileUpload.parseRequest(httpServletRequest); Iterator itemsIterator = items.iterator(); while (itemsIterator.hasNext()) { FileItem item = (FileItem) itemsIterator.next(); // Check for the file upload form item if (!item.isFormField()) { String itemNameWithoutPath = BlojsomUtils.getFilenameFromPath(item.getName()); _logger.debug( "Found file item: " + itemNameWithoutPath + " of type: " + item.getContentType()); // Is it one of the accepted file types? String fileType = item.getContentType(); boolean isAcceptedFileType = _acceptedFileTypes.containsKey(fileType); String extension = BlojsomUtils.getFileExtension(itemNameWithoutPath); boolean isAcceptedFileExtension = true; for (int i = 0; i < _invalidFileExtensions.length; i++) { String invalidFileExtension = _invalidFileExtensions[i]; if (itemNameWithoutPath.indexOf(invalidFileExtension) != -1) { isAcceptedFileExtension = false; break; } } // If so, upload the file to the resources directory if (isAcceptedFileType && isAcceptedFileExtension) { if (!resourceDirectory.exists()) { if (!resourceDirectory.mkdirs()) { _logger.error( "Unable to create resource directory for user: "******"Unable to create resource directory"); return entries; } } File resourceFile = new File( _blojsomConfiguration.getInstallationDirectory() + _resourcesDirectory + user.getId() + "/" + itemNameWithoutPath); try { item.write(resourceFile); } catch (Exception e) { _logger.error(e); addOperationResultMessage( context, "Unknown error in file upload: " + e.getMessage()); } String resourceURL = user.getBlog().getBlogBaseURL() + _blojsomConfiguration.getResourceDirectory() + user.getId() + "/" + item.getName(); _logger.debug("Successfully uploaded resource file: " + resourceFile.toString()); addOperationResultMessage( context, "Successfully upload resource file: " + item.getName() + ". <p></p>Here is a link to <a href=\"" + resourceURL + "\">" + item.getName() + "</a>. Right-click and copy the link to the resource to use in a blog entry."); } else { if (!isAcceptedFileExtension) { _logger.error("Upload file does not have an accepted extension: " + extension); addOperationResultMessage( context, "Upload file does not have an accepted extension: " + extension); } else { _logger.error( "Upload file is not an accepted type: " + item.getName() + " of type: " + item.getContentType()); addOperationResultMessage( context, "Upload file is not an accepted type: " + item.getName() + " of type: " + item.getContentType()); } } } } } catch (FileUploadException e) { _logger.error(e); addOperationResultMessage(context, "Unknown error in file upload: " + e.getMessage()); } httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE); } else if (DELETE_UPLOAD_FILES.equals(action)) { String[] filesToDelete = httpServletRequest.getParameterValues(FILE_TO_DELETE); if (filesToDelete != null && filesToDelete.length > 0) { File deletedFile; for (int i = 0; i < filesToDelete.length; i++) { String fileToDelete = filesToDelete[i]; deletedFile = new File(resourceDirectory, fileToDelete); if (!deletedFile.delete()) { _logger.debug("Unable to delete resource file: " + deletedFile.toString()); } } addOperationResultMessage( context, "Deleted " + filesToDelete.length + " file(s) from resources directory"); } httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE); } // Create a list of files in the user's resource directory Map resourceFilesMap = null; if (resourceDirectory.exists()) { File[] resourceFiles = resourceDirectory.listFiles(); if (resourceFiles != null) { resourceFilesMap = new HashMap(resourceFiles.length); for (int i = 0; i < resourceFiles.length; i++) { File resourceFile = resourceFiles[i]; resourceFilesMap.put(resourceFile.getName(), resourceFile.getName()); } } } else { resourceFilesMap = new HashMap(); } resourceFilesMap = new TreeMap(resourceFilesMap); context.put(PLUGIN_ADMIN_FILE_UPLOAD_FILES, resourceFilesMap); return entries; }
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub // super.doPost(req, resp); /*FileUpload file = new FileUpload(); boolean flag = ServletFileUpload.isMultipartContent(req); System.out.println(" ismultipartContent:"+flag); file.setFileSizeMax(300); long size = file.getFileSizeMax();//单位为字节 一个汉字=2字节 System.out.println("file size:"+size); file.setHeaderEncoding("utf-8"); // ServletFileUpload. String realPath = this.getServletContext().getRealPath("/upload"); System.out.println("上传路径:"+realPath);*/ DiskFileItemFactory factroy = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factroy); // 判断提交表单的类型是否为multipart/form-data boolean isM = upload.isMultipartContent(req); if (!isM) { System.out.println("不是符合的格式!"); } BufferedInputStream bis = null; FileOutputStream fos = null; BufferedOutputStream bos = null; try { List list = upload.parseRequest(req); Iterator it = list.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); String name = item.getName(); // 这是上传的文件名称 String fieldname = item.getFieldName(); System.out.println(name + " " + fieldname); InputStream is = item.getInputStream(); long size2 = item.getSize(); System.out.println(size2 + "=size2"); bis = new BufferedInputStream(is); fos = new FileOutputStream("/home/save/" + name); bos = new BufferedOutputStream(fos); byte[] by = new byte[1024]; int len = 0; while ((len = bis.read(by)) != -1) { bos.write(by, 0, len); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { bos.close(); fos.close(); bis.close(); } // 获取上传的文件名称 // String fileNameA = req.getParameter("filename"); // int lastIndex = fileNameA.lastIndexOf("\\"); // String fileName = fileNameA.substring(lastIndex+1); /* String fileName = "test.txt"; //设定文件保存的路径 String savePath = "/home/save/"+fileName; //读取文件内容 InputStream is = req.getInputStream(); DataInputStream dis = new DataInputStream(is); int dataLength = req.getContentLength(); String contentType = req.getHeader("Content-Type"); System.out.println("ContentType:"+contentType); Enumeration<String> names = req.getHeaderNames(); while(names.hasMoreElements()){ System.out.println(names.nextElement()); } //写入读取的内容 int length = 0; int count = 0; byte[] bs = new byte[1024]; if( count < dataLength ){ System.out.println(count+"--"+length); length = dis.read(bs, length, 1024); count += length; } File outFile = new File(savePath); if(outFile.exists()){ outFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(outFile); fos.write(bs); fos.close(); dis.close(); is.close(); Writer w = resp.getWriter(); //String s = req.getParameter("filename"); //System.out.println(s); w.write("test");*/ /*DiskFileItemFactory dis = new DiskFileItemFactory(); FileUpload up = new FileUpload(factroy); up.setHeaderEncoding("utf-8"); up.setSizeMax(100); up.setFileItemFactory(dis); ServletFileUpload sf = new ServletFileUpload(); try { sf.parseRequest(req); boolean flag = ServletFileUpload.isMultipartContent(req); if (!flag) { return; } List<FileItem> li = sf.parseRequest(req); Iterator<FileItem> its = li.iterator(); while(its.hasNext()){ FileItem item = its.next(); InputStream is = item.getInputStream(); BufferedInputStream bi = new BufferedInputStream(is); OutputStream ops = item.getOutputStream(); BufferedOutputStream bo = new BufferedOutputStream(ops); int len = 0; byte[] bs = new byte[1024]; while( (len = bi.read(bs)) != -1){ bo.write(bs, 0, len); } } } catch (FileUploadException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }*/ // up.setProgressListener(); /*try { List l = up.parseRequest(req); Iterator it = l.iterator(); while(it.hasNext()){ FileItem item = (FileItem) it.next(); } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ // ���ص���Դ��� /*InputStream in = req.getInputStream(); int dataLength = req.getContentLength(); DataInputStream dis = new DataInputStream(in); //�����·�� String filename = req.getParameter("file"); System.out.println(req.getAttribute("file")); String path = req.getContextPath(); //String fileOut = path+File.separator+"upload/"; String fileOut = "/home/save/test.txt"; System.out.println("fileOut:"+fileOut+" filename:"+filename); File file = new File(fileOut); //���õ��ֽ��� byte[] bs = new byte[1024]; int length = 0; int totalLength = 0; while(totalLength < dataLength){ length = dis.read(bs, 0, 1024); totalLength += length; } //�����ļ� FileOutputStream fos = new FileOutputStream(file); fos.write(bs); fos.close(); dis.close();*/ // ���ؿͻ��� /*InputStream in = req.getInputStream(); int dataLength = req.getContentLength(); DataInputStream dis = new DataInputStream(in); byte[] bs = new byte[1024]; int length = 0,totalLength = 0; while(totalLength < dataLength){ length = in.read(bs, 0, 1024); totalLength += length; }*/ // resp.sendRedirect("views/test/test.jsp"); // o.write(b, off, len); // req.setCharacterEncoding("utf-8"); }
/** * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's * multipart classes (see class description). * * @param saveDir the directory to save off the file * @param servletRequest the request containing the multipart * @throws java.io.IOException is thrown if encoding fails. */ @SuppressWarnings("unchecked") @Override public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { DiskFileItemFactory fac = new DiskFileItemFactory(); // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } ProgressMonitor monitor = null; // Parse the request try { ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); monitor = new ProgressMonitor(); upload.setProgressListener(monitor); servletRequest.getSession().setAttribute(ProgressMonitor.SESSION_PROGRESS_MONITOR, monitor); List<FileItem> items = upload.parseRequest(createRequestContext(servletRequest)); for (FileItem item1 : items) { FileItem item = item1; if (log.isDebugEnabled()) { log.debug("Found item " + item.getFieldName()); } if (item.isFormField()) { if (log.isDebugEnabled()) { log.debug("Item is a normal form field"); } List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } // note: see http://jira.opensymphony.com/browse/WW-633 // basically, in some cases the charset may be null, so // we're just going to try to "other" method (no idea if this // will work) String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { if (log.isDebugEnabled()) { log.debug("Item is a file upload"); } List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (FileUploadException e) { e.printStackTrace(); if (monitor != null) monitor.abort(); log.error(e); errors.add(e.getMessage()); } catch (Exception e) { e.printStackTrace(); if (monitor != null) monitor.abort(); } }
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { long start = System.currentTimeMillis(); ServletContext ctx = getServletContext(); if (req.getCharacterEncoding() == null) req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); String accept = req.getHeader("Accept"); SerializationFormat formatter = Listener.getSerializationFormat(accept); if (formatter == null) { sendError( ctx, req, resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "no known mime type in Accept header"); return; } PrintWriter out_r = resp.getWriter(); String resp_msg = ""; // check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { sendError(ctx, req, resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "no file upload"); return; } // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { List<FileItem> items = upload.parseRequest(req); // bulk load options int threads = -1; String format = "nt"; int batchSizeMB = 1; // get store AbstractCassandraRdfHector crdf = (AbstractCassandraRdfHector) ctx.getAttribute(Listener.STORE); crdf.setBatchSize(batchSizeMB); // Process the uploaded items Iterator iter = items.iterator(); String a = ""; String graph = ""; boolean a_exists = false; String file = ""; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); if (name.equals("g")) { a_exists = true; a = new String(value); // escape if the accept header is not text/plain graph = new String(a); if (formatter.getContentType().equals("text/html")) graph = escapeHtml(a); } } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); // Process a file upload InputStream uploadedStream = item.getInputStream(); // write the inputStream to a FileOutputStream file = "/tmp/upload_bulkload_" + UUID.randomUUID(); OutputStream out = new FileOutputStream(new File(file)); int read = 0; byte[] bytes = new byte[1024]; while ((read = uploadedStream.read(bytes)) != -1) { out.write(bytes, 0, read); } uploadedStream.close(); out.flush(); out.close(); resp_msg += "Bulkload " + fileName + ", size " + sizeInBytes; } } if (!a_exists || a == null || a.isEmpty()) { sendError( ctx, req, resp, HttpServletResponse.SC_BAD_REQUEST, "Please pass also the graph name as 'g' parameter"); } else { if (!a.startsWith("<") || !a.endsWith(">")) { sendError( ctx, req, resp, HttpServletResponse.SC_BAD_REQUEST, "Please pass a resource as the graph name."); return; } // load here // note: if threads==-1, it will be then set to the number of hosts if (crdf.bulkLoad(new File(file), format, threads, Store.encodeKeyspace(a)) == 1) sendError( ctx, req, resp, HttpServletResponse.SC_CONFLICT, "Graph " + graph + " does not exist yet. Please create it before bulk loading."); else { resp_msg = "Graph " + graph + " time " + (System.currentTimeMillis() - start) + "ms"; sendResponse(ctx, req, resp, HttpServletResponse.SC_BAD_REQUEST, resp_msg); _log.info(resp_msg); } } // delete the tmp file new File(file).delete(); out_r.println(resp_msg); out_r.close(); } catch (FileUploadException ex) { ex.printStackTrace(); return; } catch (StoreException ex) { ex.printStackTrace(); return; } return; }
public Object onUploadException(FileUploadException exception) { message = "Upload exception: " + exception.getMessage(); return this; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String contextPath = getServletContext().getRealPath(File.separator + "images_shop" + File.separator); String uploadPath = File.separator + "upload" + File.separator; String tmpPath = "tmp" + File.separator; String path = null; DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1024 * 1024 * 10); fileItemFactory.setRepository(new File(contextPath + tmpPath)); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); List<FileItem> items = null; try { items = servletFileUpload.parseRequest(req); } catch (FileUploadException e) { e.printStackTrace(); } Map<String, String> productMap = new HashMap<String, String>(); for (FileItem item : items) { if (item.isFormField()) { productMap.put(item.getFieldName(), item.getString("utf-8")); } } for (FileItem item : items) { if (!item.isFormField() && !item.getName().isEmpty()) { int hashCode = item.hashCode(); int d1 = hashCode & 0xff; int d2 = hashCode >> 8 & 0xff; String filePath = contextPath + uploadPath + d1 + File.separator + d2; System.out.println(filePath); File file = new File(filePath); if (!file.isDirectory()) { file.mkdirs(); } String fileName = UUID.randomUUID().toString() + item.getName().substring(item.getName().lastIndexOf(".")); File saveFile = new File(file, fileName); InputStream is = item.getInputStream(); FileOutputStream os = new FileOutputStream(saveFile); IOUtil.in2out(is, os); IOUtil.close(is, os); item.delete(); path = "images_shop/upload/" + d1 + "/" + d2 + "/" + fileName; } } HttpSession session = req.getSession(); Integer shopId = (Integer) session.getAttribute(AttrName.SessionScope.SHOPID); String productName = productMap.get("product_name"); String category = productMap.get("category"); String price = productMap.get("price"); String stockNum = productMap.get("stock_num"); String description = productMap.get("description"); if (shopId == null) { resp.sendRedirect("myshop"); ; return; } if (productName == null || "".trim().equals(productName) || category == null || "".trim().equals(category) || price == null || "".equals(price) || stockNum == null || "".trim().equals(stockNum) || description == null || "".trim().equals(description)) { System.out.println("1asas"); req.getRequestDispatcher("/WEB-INF/shopowner/add_products.jsp").forward(req, resp); return; } Product product = new Product(); product.setName(productName); product.setCategory(category); product.setPrice(Double.valueOf(price)); product.setDiscountPrice(Double.valueOf(price)); product.setShopId(shopId); product.setStockNum(Integer.parseInt(stockNum)); product.setDescription(description); if (path == null || "".trim().equals(path)) { product.setPicture("images_shop/index.jpg"); } else { product.setPicture(path); } boolean insert = productService.insert(product); req.setAttribute("img", product.getPicture()); if (insert == true) { resp.sendRedirect("selectedshop"); return; } else { resp.sendRedirect("addproduct"); } }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> itens; try { itens = (ArrayList<FileItem>) upload.parseRequest(req); // Nome Completo String nomeCompleto = itens.get(0).getString("UTF-8"); // Email String email = itens.get(1).getString("UTF-8"); // Senha String senha = itens.get(2).getString("UTF-8"); // Apelido String apelido = itens.get(3).getString("UTF-8"); // Estado String estado = itens.get(4).getString("UTF-8"); // Cidade String cidade = itens.get(5).getString("UTF-8"); // Data String data = itens.get(6).getString("UTF-8"); // FotoDePerfil String realPath = getServletContext().getRealPath("/imagensPerfil"); String nomeImagem = apelido; String foto; if (itens.get(7).getString().equals("")) { foto = "imagens/user.png"; } else { new GerenciadorImagem().inserirImagemPerfil(itens.get(7), realPath, nomeImagem); foto = "imagensPerfil/" + nomeImagem + ".jpg"; } Usuario u = new Usuario( email, senha, nomeCompleto, apelido, Date.valueOf(data), cidade, estado, true, foto); boolean cadastrou = new GerenciadorUsuario().adicionar(u); req.setAttribute("cadastrou", cadastrou); req.setAttribute("emailCadastro", email); } catch (FileUploadException ex) { ex.printStackTrace(); } } req.getRequestDispatcher("cadastro.jsp").forward(req, resp); }
// uplaod api @Override @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @Transactional(propagation = Propagation.NESTED) public Response saveImage(@Context HttpServletRequest request) { String comment = null; // Token tokenObj = (Token) request.getAttribute("token"); // byte[] image = null; InputStream is = null; BufferedOutputStream out = null; String path = null; try { ServletFileUpload servletFileUpload = new ServletFileUpload(); FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request); while (fileItemIterator.hasNext()) { FileItemStream fileItemStream = fileItemIterator.next(); if ("comment".equals(fileItemStream.getFieldName())) { StringWriter stringWriter = new StringWriter(); IOUtils.copy(fileItemStream.openStream(), stringWriter, "utf-8"); comment = stringWriter.toString(); } else if ("content".equals(fileItemStream.getFieldName())) { path = createPath(); // save image content // path = ("/Users/aoden/Desktop/aaaaaa.jpg"); is = fileItemStream.openStream(); out = new BufferedOutputStream(new FileOutputStream(path)); int data = -1; while ((data = is.read()) != -1) { out.write(data); } } } Token tokenObj = (Token) request.getAttribute("token"); Photo photo = new Photo(); photo.setComment(comment); photo.setPath(path); photo.setUser(tokenObj.getUser()); photoDao.save(photo); return Response.status(500).entity(buildDTO(200, null)).build(); // User user = tokenObj.getUser(); } catch (HibernateException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } catch (FileUploadException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } catch (IOException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } finally { // close the streams if (is != null) try { is.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }