@Override protected void service() throws ServletException, IOException { HttpServletRequest request = getRequest(); String path = null; DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024, new File(Configuration.getContextPath("temp"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(3 * 1024 * 1024); try { List<FileItem> items = upload.parseRequest(request); FileItem fileItem = null; if (items != null && items.size() > 0 && StringUtils.isNotBlank((fileItem = items.get(0)).getName())) { String fileName = fileItem.getName(); if (!fileName.endsWith(".jpg") && !fileName.endsWith(".gif") && !fileName.endsWith(".png")) { writeText("format_error"); return; } path = ImageUtil.generatePath(fileItem.getName()); IOUtil.copy(fileItem.getInputStream(), Configuration.getContextPath(path)); fileItem.delete(); writeText(Configuration.getSiteUrl(path)); } } catch (FileUploadException e) { throw new RuntimeException(e); } }
public void close() { if (!isEmpty()) { for (Object v : values()) { if (v instanceof FileItem) ((FileItem) v).delete(); } clear(); } }
private static void deleteFileItem(FileItem fileItem, int scope) { if (logger.isDebugEnabled() && fileItem instanceof DiskFileItem) { final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation(); if (storeLocation != null) { final String temporaryFileName = storeLocation.getAbsolutePath(); final String scopeString = (scope == REQUEST_SCOPE) ? "request" : (scope == SESSION_SCOPE) ? "session" : "application"; logger.debug("Deleting temporary " + scopeString + "-scoped file: " + temporaryFileName); } } fileItem.delete(); }
/** Uploads a plugin. */ public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, ServletException { try { Jenkins.getInstance().checkPermission(UPLOAD_PLUGINS); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); // Parse the request FileItem fileItem = (FileItem) upload.parseRequest(req).get(0); String fileName = Util.getFileName(fileItem.getName()); if ("".equals(fileName)) { return new HttpRedirect("advanced"); } // we allow the upload of the new jpi's and the legacy hpi's if (!fileName.endsWith(".jpi") && !fileName.endsWith(".hpi")) { throw new Failure(hudson.model.Messages.Hudson_NotAPlugin(fileName)); } // first copy into a temporary file name File t = File.createTempFile("uploaded", ".jpi"); t.deleteOnExit(); fileItem.write(t); fileItem.delete(); final String baseName = identifyPluginShortName(t); pluginUploaded = true; // Now create a dummy plugin that we can dynamically load (the InstallationJob will force a // restart if one is needed): JSONObject cfg = new JSONObject() .element("name", baseName) .element("version", "0") . // unused but mandatory element("url", t.toURI().toString()) .element("dependencies", new JSONArray()); new UpdateSite(UpdateCenter.ID_UPLOAD, null).new Plugin(UpdateCenter.ID_UPLOAD, cfg) .deploy(true); return new HttpRedirect("../updateCenter"); } catch (IOException e) { throw e; } catch (Exception e) { // grrr. fileItem.write throws this throw new ServletException(e); } }
/** * Removes all FileItems stored in session, but in this case the user can specify whether the * temporary data is removed from disk. * * @param request * @param removeData true: the file data is deleted. false: use it when you are referencing file * items instead of copying them. */ public static void removeSessionFileItems(HttpServletRequest request, boolean removeData) { logger.debug( "UPLOAD-SERVLET (" + request.getSession().getId() + ") removeSessionFileItems: removeData=" + removeData); @SuppressWarnings("unchecked") Vector<FileItem> sessionFiles = (Vector<FileItem>) request.getSession().getAttribute(ATTR_FILES); if (removeData && sessionFiles != null) { for (FileItem fileItem : sessionFiles) { if (fileItem != null && !fileItem.isFormField()) { fileItem.delete(); } } } request.getSession().removeAttribute(ATTR_FILES); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL); if (ServletFileUpload.isMultipartContent(req)) { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); // fileItemFactory.setSizeThreshold(0); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); List<FileItem> fileItemsList; try { fileItemsList = (List<FileItem>) servletFileUpload.parseRequest(req); } catch (FileUploadException e) { writeExceptionResponse(resp, "File upload failed", e); return; } List<FileItem> actualFiles = new ArrayList<FileItem>(); Map<String, String> formFields = new HashMap<String, String>(); boolean retrieve = false; Subject authenticatedSubject = null; for (FileItem fileItem : fileItemsList) { if (fileItem.isFormField()) { if (fileItem.getFieldName() != null) { formFields.put(fileItem.getFieldName(), fileItem.getString()); } if ("retrieve".equals(fileItem.getFieldName())) { retrieve = true; } else if ("sessionid".equals(fileItem.getFieldName())) { int sessionid = Integer.parseInt(fileItem.getString()); SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager(); try { authenticatedSubject = subjectManager.getSubjectBySessionId(sessionid); } catch (Exception e) { throw new ServletException("Cannot authenticate request", e); } } fileItem.delete(); } else { // file item contains an actual uploaded file actualFiles.add(fileItem); log("file was uploaded: " + fileItem.getName()); } } if (authenticatedSubject == null) { for (FileItem fileItem : actualFiles) { fileItem.delete(); } throw new ServletException("Cannot process unauthenticated request"); } if (retrieve && actualFiles.size() == 1) { // sending in "retrieve" form element with a single file means the client just wants the // content echoed back resp.setContentType("text/html"); FileItem fileItem = actualFiles.get(0); ServletOutputStream outputStream = resp.getOutputStream(); outputStream.print("<html>"); InputStream inputStream = fileItem.getInputStream(); try { // we have to HTML escape inputStream before writing it to outputStream StreamUtil.copy(inputStream, outputStream, false, true); } finally { inputStream.close(); } outputStream.print("</html>"); outputStream.flush(); fileItem.delete(); } else { Map<String, File> allUploadedFiles = new HashMap<String, File>(); // maps form field name to the actual file Map<String, String> allUploadedFileNames = new HashMap<String, String>(); // maps form field name to upload file name for (FileItem fileItem : actualFiles) { File theFile = forceToFile(fileItem); allUploadedFiles.put(fileItem.getFieldName(), theFile); allUploadedFileNames.put( fileItem.getFieldName(), (fileItem.getName() != null) ? fileItem.getName() : theFile.getName()); } processUploadedFiles( authenticatedSubject, allUploadedFiles, allUploadedFileNames, formFields, req, resp); } } }
@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"); } }
/** The POST request.EPCUpload.java */ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException { PrintWriter out = null; FileItem fileItem = null; try { String oryxBaseUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/oryx/"; // Get the PrintWriter res.setContentType("text/plain"); res.setCharacterEncoding("utf-8"); out = res.getWriter(); // No isMultipartContent => Error final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req); if (!isMultipartContent) { printError(out, "No Multipart Content transmitted."); return; } // Get the uploaded file final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setSizeMax(-1); final List<?> items; items = servletFileUpload.parseRequest(req); if (items.size() != 1) { printError(out, "Not exactly one File."); return; } fileItem = (FileItem) items.get(0); // replace dtd reference by existing reference /oryx/lib/ARIS-Export.dtd String amlStr = fileItem.getString("UTF-8"); amlStr = amlStr.replaceFirst("\"ARIS-Export.dtd\"", "\"" + oryxBaseUrl + "lib/ARIS-Export.dtd\""); FileOutputStream fileout = null; OutputStreamWriter outwriter = null; try { fileout = new FileOutputStream(((DiskFileItem) fileItem).getStoreLocation()); outwriter = new OutputStreamWriter(fileout, "UTF-8"); outwriter.write(amlStr); outwriter.flush(); } finally { if (outwriter != null) outwriter.close(); if (fileout != null) fileout.close(); } // parse AML file AMLParser parser = new AMLParser(((DiskFileItem) fileItem).getStoreLocation().getAbsolutePath()); parser.parse(); Collection<EPC> epcs = new HashSet<EPC>(); Iterator<String> ids = parser.getModelIds().iterator(); while (ids.hasNext()) { String modelId = ids.next(); epcs.add(parser.getEPC(modelId)); } // serialize epcs to eRDF oryx format OryxSerializer oryxSerializer = new OryxSerializer(epcs, oryxBaseUrl); oryxSerializer.parse(); Document outputDocument = oryxSerializer.getDocument(); // get document as string String docAsString = ""; Source source = new DOMSource(outputDocument); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transformer = tfactory.newTransformer(); transformer.transform(source, result); docAsString = stringWriter.getBuffer().toString(); // write response out.print("" + docAsString + ""); } catch (Exception e) { handleException(out, e); } finally { if (fileItem != null) { fileItem.delete(); } } }
/** * Called by the connector servlet to handle a {@code POST} request. In particular, it handles the * {@link Command#FILE_UPLOAD FileUpload} and {@link Command#QUICK_UPLOAD QuickUpload} commands. * * @param request the current request instance * @return the upload response instance associated with this request */ @SuppressWarnings("unchecked") UploadResponse doPost(final HttpServletRequest request) { Dispatcher.logger.debug("Entering Dispatcher#doPost"); final Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) { uploadResponse = UploadResponse.getFileUploadDisabledError(); } else if (!Command.isValidForPost(context.getCommandStr())) { uploadResponse = UploadResponse.getInvalidCommandError(); } else if (!ResourceType.isValidType(context.getTypeStr())) { uploadResponse = UploadResponse.getInvalidResourceTypeError(); } else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } else { // call the Connector#fileUpload final ResourceType type = context.getDefaultResourceType(); final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); try { final List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time final FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename final String fileName = FilenameUtils.getName(uplFile.getName()); Dispatcher.logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); final String newFileName = this.connector.fileUpload( type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); final String fileUrl = UtilsResponse.fileUrl( RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); if (sanitizedFileName.equals(newFileName)) { uploadResponse = UploadResponse.getOK(fileUrl); } else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } catch (final InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (final WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (final IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (final FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } Dispatcher.logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
/** * 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 { response.setHeader("Expires", "-1"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-control", "no-cache"); response.setHeader("Content-Type", "text/html; charset=utf-8"); request.setCharacterEncoding("UTF-8"); ArrayList parts = (ArrayList) request.getSession().getAttribute("attachments"); if (parts == null) { parts = new ArrayList(); } String fileName = null; try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setRepository(new File(tmpDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MAX_SIZE); // Parse the request List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { // String fieldName = item.getFieldName(); fileName = item.getName(); // ie6 bug. it sends whole file path as file name. use firefox! if (fileName.indexOf("\\") >= 0) { fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); } File uploadDir = WebdiskController.getUploadDir(getAuthProfile(request).getUsername()); File uploadedFile = new File(uploadDir.getAbsolutePath() + "/" + fileName); item.write(uploadedFile); uploadedFile = null; if (fileName.indexOf("\\") > 0) { fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); } item.delete(); } } response.sendRedirect("../upload_file_ok.jsp?result=0"); } catch (SizeLimitExceededException e) { // attachment exceeded the attachment upload size limit response.sendRedirect( "../upload_file_ok.jsp?result=1&maxAttSize=" + Utility.sizeToHumanReadable(MAX_SIZE)); } catch (Exception e) { response.sendRedirect("../upload_file_ok.jsp?result=3"); } }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); // 设置存储位置 String upload = this.getServletContext().getRealPath("/upload"); String temp = this.getServletContext().getRealPath("/temp"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 5); // 100k--进入缓存的入口大小 factory.setRepository(new File(temp)); ServletFileUpload fileUpload = new ServletFileUpload(factory); fileUpload.setHeaderEncoding("UTF-8"); fileUpload.setFileSizeMax(1024 * 1024 * 3); // fileUpload.setSizeMax(1024 * 1024 * 5); System.out.println("upload:" + upload); // 5、检查是否为正确的表单上传方式---enctype="multipart/form-data" if (!ServletFileUpload.isMultipartContent(request)) { throw new RuntimeException("请使用正确的表单提交方式"); } try { List<FileItem> list = fileUpload.parseRequest(request); for (FileItem fileItem : list) { if (fileItem.isFormField()) { // 字段 } else { // 文件 String name = fileItem.getName(); String strUUID = UUID.randomUUID().toString(); if (name.endsWith(".jpg") || name.endsWith(".png") || name.endsWith(".gif")) { strUUID += "_picture" + name.substring(name.lastIndexOf(".")); // 设置文件输出流 try { InputStream is = fileItem.getInputStream(); // 获取文件流 OutputStream os = new FileOutputStream(new File(upload, strUUID)); // 将文件存储到服务器响应位置 IOUtils.In2Out(is, os); IOUtils.close(is, os); // 删除temp中缓存的文件 fileItem.delete(); // 将图片信息存储到数据库 } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("输出流异常"); } } } } } catch (FileSizeLimitExceededException e) { System.out.println("file size is not allowed"); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.getWriter().append("Served at: ").append(request.getContextPath()); }
/** * 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 { Map<String, Object> params = new HashMap<String, Object>(); PrintWriter outP = response.getWriter(); response.setContentType("text/html"); request.setCharacterEncoding("utf-8"); String path = request.getContextPath(); String serverPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/video/"; DiskFileItemFactory factory = new DiskFileItemFactory(); String videoSavePath = request.getSession().getServletContext().getRealPath("/video") + File.separator; String response_video_path = ""; String video_img_path = ""; factory.setRepository(new File(videoSavePath)); factory.setSizeThreshold(1024 * 1024 * 10); ServletFileUpload upload = new ServletFileUpload(factory); // 调用 parseRequest(request)方法 获得上传文件 FileItem 的集合list 可实现多文件上传。 try { @SuppressWarnings("unchecked") List<FileItem> list = (List<FileItem>) upload.parseRequest(request); for (FileItem item : list) { // 如果获取的表单信息是普通的文本信息。即通过页面表单形式传递来的字符串。 if (item.isFormField()) { // 获取表单属性名字。 String name = item.getFieldName(); // 获取用户具体输入的字符串, String value = item.getString(); request.setAttribute(name, value); } // 如果传入的是非简单字符串,而是图片,音频,视频等二进制文件。 else { // 获取路径名 String value = item.getName(); System.out.println("path:" + value); String fileName = DateUtils.getUpLoadFileName() + value.substring(value.lastIndexOf(".")); if (fileName.endsWith(".jpg")) { video_img_path = serverPath + fileName; System.out.println(video_img_path); } else { response_video_path = serverPath + fileName; } // request.setAttribute(name, filename); /* * 第三方提供的方法直接写到文件中。 item.write(new File(path,filename)); */ // 收到写到接收的文件中。 OutputStream out = new FileOutputStream(new File(videoSavePath, fileName)); InputStream in = item.getInputStream(); int length = 0; byte[] buf = new byte[1024]; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); } in.close(); out.close(); item.delete(); } } } catch (Exception e) { System.out.println(e.toString()); params.put("err", ErrorEnum.INVALID.name()); params.put("rt", 0); outP.print(JsonUtil.toJsonString(params)); outP.flush(); outP.close(); return; } int cid = Integer.valueOf(request.getAttribute("cid").toString()); int publisher_id = Integer.valueOf(request.getAttribute("user_id").toString()); Video video = new Video(); video.setCid(cid); video.setPublisher_id(publisher_id); video.setVideo_img(video_img_path); video.setVideo_path(response_video_path); video.setVideo_duration(Integer.valueOf(request.getAttribute("video_duration").toString())); video.setVideo_size(Integer.valueOf(request.getAttribute("video_size").toString())); video.setVideo_content(request.getAttribute("video_content").toString()); video.setTime(request.getAttribute("time").toString()); VideoDao dao = VideoDaoFactory.getInstances(); dao.insertVidoeToDB(video); params.put("rt", 1); params.put("video_path", response_video_path); params.put("video_img_path", video_img_path); outP.print(JsonUtil.toJsonString(params)); outP.flush(); outP.close(); System.out.println(JsonUtil.toJsonString(params)); }
/** * If any of these files exist, delete them. * * @param tempFiles The file items to delete. */ protected void deleteTempFiles(List<FileItem> tempFiles) { for (FileItem item : tempFiles) { item.delete(); } }
public void delete() { if (fileItem != null) fileItem.delete(); }
/** * Deletes the underlying storage for a file item, including deleting any associated temporary * disk file. Although this storage will be deleted automatically when the <code>FileItem</code> * instance is garbage collected, this method can be used to ensure that this is done at an * earlier time, thus preserving system resources. * * <p>On finalize htis method will be called. */ private void delete() { if (fileItem != null) { fileItem.delete(); } }