@Put public AttachmentResponse addAttachment(Representation entity) { if (authenticate() == false) return null; String taskId = (String) getRequest().getAttributes().get("taskId"); try { RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRepresentation(entity); FileItem uploadItem = null; for (FileItem fileItem : items) { if (fileItem.getName() != null) { uploadItem = fileItem; } } String fileName = uploadItem.getName(); Attachment attachment = ActivitiUtil.getTaskService() .createAttachment( uploadItem.getContentType(), taskId, null, fileName, fileName, uploadItem.getInputStream()); return new AttachmentResponse(attachment); } catch (Exception e) { throw new ActivitiException("Unable to add new attachment to task " + taskId); } }
@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); } }
/** * 上传一般模块的图片 * * @param items * @param dir * @return */ public static String upload(List<FileItem> items, String dir) { String filePath = ""; String fileName; Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss"); if (items == null || items.isEmpty()) { return ""; } for (FileItem item : items) { if (!item.isFormField()) { try { String type = item.getName().substring((item.getName().lastIndexOf("."))); fileName = item.getName().substring(0, item.getName().indexOf(".")); fileName = fileName + "(" + format.format(date) + ")" + type; if (!Constants.PICTURE_TYPE.contains(type.toLowerCase())) { // 限制文件上传类型 return ""; } File tempFile = new File(dir); if (!tempFile.exists()) { // 如果文件夹不存在 tempFile.mkdirs(); // 创建一个新的空文件夹 } zoomOut(item.getInputStream(), fileName, dir); filePath = dir + "\\" + fileName; } catch (Exception ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } } return filePath; }
@Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { StringBuffer response = new StringBuffer(); for (FileItem item : sessionFiles) { if (false == item.isFormField()) { try { if (item.getName().endsWith(".xls")) { POIFSFileSystem fs = new POIFSFileSystem(item.getInputStream()); HSSFWorkbook wb = new HSSFWorkbook(fs); System.out.println("Sheet Num:" + wb.getNumberOfSheets()); // only get first sheet,ignore others HSSFSheet sheet = wb.getSheetAt(0); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { HSSFRow row = (HSSFRow) rows.next(); Iterator<Cell> cells = row.cellIterator(); while (cells.hasNext()) { HSSFCell cell = (HSSFCell) cells.next(); response.append(cell.toString() + ":"); } response.append("\n"); } } else if (item.getName().endsWith(".xlsx")) { // POIFSFileSystem fs = new POIFSFileSystem(item.getInputStream()); XSSFWorkbook wb = new XSSFWorkbook(item.getInputStream()); System.out.println("Sheet Num:" + wb.getNumberOfSheets()); // only get first sheet,ignore others XSSFSheet sheet = wb.getSheetAt(0); Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); Iterator<Cell> cells = row.cellIterator(); while (cells.hasNext()) { XSSFCell cell = (XSSFCell) cells.next(); response.append(cell.toString() + ":"); } response.append("\n"); } } } catch (Exception e) { throw new UploadActionException(e); } } } // / Remove files from session because we have a copy of them removeSessionFileItems(request); // / Send your customized message to the client. return response.toString(); }
/** * Responsible for constructing a FileBean object for the named file parameter. If there is no * file parameter with the specified name this method should return null. * * @param name the name of the file parameter * @return a FileBean object wrapping the uploaded file */ public FileBean getFileParameterValue(String name) { final FileItem item = this.files.get(name); if (item == null || ((item.getName() == null || item.getName().length() == 0) && item.getSize() == 0)) { return null; } else { // Attempt to ensure the file name is just the basename with no path included String filename = item.getName(); int index; if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find()) { index = filename.lastIndexOf('\\'); } else { index = filename.lastIndexOf('/'); } if (index >= 0 && index + 1 < filename.length() - 1) { filename = filename.substring(index + 1); } // Use an anonymous inner subclass of FileBean that overrides all the // methods that rely on having a File present, to use the FileItem // created by commons upload instead. return new FileBean(null, item.getContentType(), filename, this.charset) { @Override public long getSize() { return item.getSize(); } @Override public InputStream getInputStream() throws IOException { return item.getInputStream(); } @Override public void save(File toFile) throws IOException { try { item.write(toFile); delete(); } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } else { IOException ioe = new IOException("Problem saving uploaded file."); ioe.initCause(e); throw ioe; } } } @Override public void delete() throws IOException { item.delete(); } }; } }
@Test public void testDoHandleRequest() { WFileWidget widget = new WFileWidget(); setActiveContext(createUIContext()); // Request - with file (changed) MockRequest request = setupFileUploadRequest(widget, TEST_FILE_ITEM); boolean changed = widget.doHandleRequest(request); Assert.assertTrue("Request With File - Widget should have changed", changed); Assert.assertEquals( "Request With File - Incorrect file item returned", TEST_FILE_ITEM.getName(), widget.getValue().getName()); // Request - with same file (still change as any file uploaded is a change) request = setupFileUploadRequest(widget, TEST_FILE_ITEM); changed = widget.doHandleRequest(request); Assert.assertTrue( "Request With Same File - Widget should have changed as any file upload is considered a change", changed); Assert.assertEquals( "Request With Same File - Incorrect file item returned", TEST_FILE_ITEM.getName(), widget.getValue().getName()); // Request - with different file (change) request = setupFileUploadRequest(widget, TEST_FILE_ITEM2); changed = widget.doHandleRequest(request); Assert.assertTrue("Request With Different File - Widget should have changed", changed); Assert.assertEquals( "Request With Different File - Incorrect file item returned", TEST_FILE_ITEM2.getName(), widget.getValue().getName()); // Request - no file (change) request = setupFileUploadRequest(widget, TEST_EMPTY_FILE_ITEM); changed = widget.doHandleRequest(request); Assert.assertTrue("Request With Empty File - Widget should have changed", changed); Assert.assertNull("Request With Empty File - Incorrect file item returned", widget.getValue()); // Request - no file (no change) request = setupFileUploadRequest(widget, TEST_EMPTY_FILE_ITEM); changed = widget.doHandleRequest(request); Assert.assertFalse("Request With Empty File - Widget should have not changed", changed); Assert.assertNull("Request With Empty File - Incorrect file item returned", widget.getValue()); }
protected void processFile(FileItem item, String name, MutableRequest request) { try { String fileName = FilenameUtils.getName(item.getName()); UploadedFile upload = new DefaultUploadedFile( item.getInputStream(), fileName, item.getContentType(), item.getSize()); request.setParameter(name, name); request.setAttribute(name, upload); logger.debug("Uploaded file: {} with {}", name, upload); } catch (IOException e) { throw new InvalidParameterException("Can't parse uploaded file " + item.getName(), e); } }
/** * 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(); } }
public File doAttachment(HttpServletRequest request) throws ServletException, IOException { File file = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<?> items = upload.parseRequest(request); Iterator<?> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { parameters .put(item.getFieldName(), item.getString("UTF-8")); } else { File tempFile = new File(item.getName()); file = new File(sc.getRealPath("/") + savePath, tempFile .getName()); item.write(file); } } } catch (Exception e) { Logger logger = Logger.getLogger(SendAttachmentMailServlet.class); logger.error("邮件发送出了异常", e); } return file; }
@Issue("JENKINS-30941") @Test public void cleanUpSucceeds() throws Exception { /** Issue was just present on Linux not windows - but the test will run on both */ final String credentialsId = "zipfile"; /* do the dance to get a simple zip file into jenkins */ InputStream zipStream = this.getClass().getResourceAsStream("a.zip"); try { assertThat(zipStream, is(not(nullValue()))); File zip = tmp.newFile("a.zip"); FileUtils.copyInputStreamToFile(zipStream, zip); FileItem fi = new FileItemImpl(zip); FileCredentialsImpl fc = new FileCredentialsImpl( CredentialsScope.GLOBAL, credentialsId, "Just a zip file", fi, fi.getName(), null); CredentialsProvider.lookupStores(j.jenkins) .iterator() .next() .addCredentials(Domain.global(), fc); } finally { IOUtils.closeQuietly(zipStream); zipStream = null; } final String unixFile = "/dir/testfile.txt"; final String winFile = unixFile.replace( "/", "\\\\"); /* two \\ as we escape the code and then escape for the script */ // if this file does not have a line ending then the text is not echoed to the log. // fixed in workflow 1.11+ (which is not released at the time of writing) final String contents = "Test of ZipFileBinding\n"; WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition( new CpsFlowDefinition( "" + "node {\n" + " withCredentials([[$class: 'ZipFileBinding', credentialsId: '" + credentialsId + "', variable: 'ziploc']]) {\n" + (Functions.isWindows() ? " bat 'type %ziploc%" + winFile + "'\n" : " sh 'cat ${ziploc}" + unixFile + "'\n") + " def text = readFile encoding: 'UTF-8', file: \"${env.ziploc}" + unixFile + "\"\n" + " if (!text.equals('''" + contents + "''')) {\n" + " error ('incorrect details from zip file')\n" + " }\n" + " }\n" + "}\n", true)); WorkflowRun run = p.scheduleBuild2(0).get(); j.assertBuildStatusSuccess(run); j.assertLogContains(contents, run); }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { if (!ServletFileUpload.isMultipartContent(request)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { List<FileItem> files = uploadHandler.parseRequest(request); if (files.size() == 0) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } FileItem fileItem = files.get(0); if (!fileItem.getContentType().equals(Constants.CLASS_CONTENT_TYPE) || fileItem.isFormField()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } String folderName = baseDir + request.getRequestURI().replaceAll("/", Constants.FILE_SEPARATOR); File folder = new File(folderName); if (folder.exists() && !folder.isDirectory()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (!folder.exists()) { folder.mkdirs(); } fileItem.write(new File(folderName + Constants.FILE_SEPARATOR + fileItem.getName())); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } }
@Test public void testGetRequestValue() { WFileWidget widget = new WFileWidget(); setActiveContext(createUIContext()); // Set current file widget.setData(TEST_FILE_ITEM_WRAP); // Empty Request - should return current value FileUploadMockRequest request = new FileUploadMockRequest(); Assert.assertEquals( "Empty request should return the current value", TEST_FILE_ITEM_WRAP, widget.getRequestValue(request)); // File on the request request = setupFileUploadRequest(widget, TEST_FILE_ITEM2); Assert.assertEquals( "Request with a file item should return the file on the request", TEST_FILE_ITEM2.getName(), widget.getRequestValue(request).getName()); // Empty File on the request request = setupFileUploadRequest(widget, TEST_EMPTY_FILE_ITEM); Assert.assertNull( "Request with an empty file item should return null", widget.getRequestValue(request)); }
/** * Override executeAction to save the received files in a custom place and delete this items from * session. */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { String response = ""; HttpSession session = request.getSession(true); if (sessionFiles.size() == 0) { LOG.info("No hay imagenes en la session"); return "No hay imagenes en la session"; } if (session.getAttribute(ATTR_ARCHIVOS) == null) session.setAttribute(ATTR_ARCHIVOS, new ArrayList<String>()); List<String> photos = (List<String>) session.getAttribute(ATTR_ARCHIVOS); for (FileItem item : sessionFiles) { if (false == item.isFormField()) { try { // / Create a new file based on the remote file name in the // client // String saveName = // item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", // "_"); // File file =new File("/tmp/" + saveName); // / Create a temporary file placed in /tmp (only works in // unix) // File file = File.createTempFile("upload-", ".bin", new // File("/tmp")); // / Create a temporary file placed in the default system // temp folder String name = item.getName(); int posPunto = name.lastIndexOf("."); String ext = name.substring(posPunto + 1); File file = File.createTempFile("gha", "." + ext); item.write(file); // / Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); photos.add(file.getName()); // / Send a customized message to the client. response += file.getName(); } catch (Exception e) { throw new UploadActionException(e); } } } // / Remove files from session because we have a copy of them removeSessionFileItems(request); // / Send your customized message to the client. return response; }
private FileTemp getFileInfo(HttpServletRequest request, HttpServletResponse response) throws IOException { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); String status = ""; InputStream is = null; String fileName = ""; for (Iterator<FileItem> i = items.iterator(); i.hasNext(); ) { FileItem item = i.next(); if (item.isFormField()) { if (item.getFieldName().equals("status_text")) { status = new String(item.get()); } } else { fileName = item.getName(); is = item.getInputStream(); } } return new FileTemp(fileName, is, status); } catch (FileUploadException e) { return null; } }
/** * 上传文件, 调用该方法之前必须先调用 parseRequest(HttpServletRequest request) * * @param parent 存储的目录 * @throws Exception */ public void upload(File parent) throws Exception { if (fileItem == null) return; String name = fileItem.getName(); File file = new File(parent, name); uploadFile(file); }
@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(); } }
public Photo saveImg(FileItem item) throws Exception { Photo photo = new Photo(); String filename = item.getName(); if (filename == null || filename.length() == 0) { log.error("img name illegal"); return null; } int index = filename.lastIndexOf("."); String type = filename.substring(index + 1); if (!ImgTools.checkImgFormatValidata(type)) { log.error("img type illegal"); return null; } ObjectId id = ObjectIdGenerator.generate(); // filename = new ObjectId() + filename.substring(index); photo.setId(id.toString()); photo.setType(type); GridFS mphoto = new GridFS(MongoDBPool.getInstance().getDB(), collection); GridFSInputFile in = null; in = mphoto.createFile(item.getInputStream()); in.setId(id); in.setFilename(id.toString()); in.setContentType(type); in.save(); item.getInputStream().close(); return photo; }
public static final File writeFileItemToFolder( FileItem fileItem, File folder, boolean overwrite, boolean rename) throws IOException { if (!folder.isDirectory()) { return null; } File file = new File( URLHelper.mergePath( folder.getAbsolutePath(), StringHelper.createFileName(StringHelper.getFileNameFromPath(fileItem.getName())))); if (!file.exists()) { file.createNewFile(); } else { if (!overwrite && !rename) { throw new FileExistsException("File already exists."); } if (rename) { file = ResourceHelper.getFreeFileName(file); } } InputStream in = null; try { in = fileItem.getInputStream(); writeStreamToFile(in, file); return file; } catch (IOException e) { ResourceHelper.closeResource(in); file.delete(); throw e; } finally { ResourceHelper.closeResource(in); } }
/** * Returns the original filename in the client's filesystem, as provided by the browser (or other * client software). In most cases, this will be the base file name, without path information. * However, some clients, such as the Opera browser, do include path information. */ public String getFileName() { String result = null; if (fileItem != null) { result = fileItem.getName(); } return result; }
private void parseRequest( HttpServletRequest request, Map<String, String> parameters, List<file> files) throws IOException { if (ServletFileUpload.isMultipartContent(request)) { List<FileItem> fileItems = parseMultipartRequest(request); long fileSizeMaxMB = ServerConfig.webServerUploadMax(); long fileSizeMax = fileSizeMaxMB > 0 ? fileSizeMaxMB * NumericUtils.Megabyte : Long.MAX_VALUE; for (FileItem fileItem : fileItems) { if (!fileItem.isFormField()) { if (fileItem.getSize() > fileSizeMax) throw new RuntimeException( Resources.format( "Exception.fileSizeLimitExceeded", fileItem.getName(), fileSizeMaxMB)); files.add(new file(fileItem)); } else parameters.put(fileItem.getFieldName(), fileItem.getString(encoding.Default.toString())); } } else { @SuppressWarnings("unchecked") Map<String, String[]> requestParameters = request.getParameterMap(); for (String name : requestParameters.keySet()) { String[] values = requestParameters.get(name); parameters.put(name, values.length != 0 ? values[0] : null); } } parameters.put(Json.ip.get(), request.getRemoteAddr()); }
public void decodeSimple(FacesContext context, FileUpload fileUpload, FileItem file) { if (file.getName().equals("")) { fileUpload.setSubmittedValue(""); } else { fileUpload.setSubmittedValue(new DefaultUploadedFile(file)); } }
public Map upload(HttpServletRequest request, FileItem item) { Map mapList = new HashMap(); try { if (item.isFormField()) { // 普通表单 } else { String fieldName = item.getFieldName(); String fileName = item.getName(); // 如果文件域没有填写内容,或者填写的文件不存在 if ("".equals(fileName) || item.getSize() == 0) { return mapList; } String userfilepath = request.getRealPath("upload"); String date = "/" + fnu.getDate8() + "/"; String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); String newfilename = fnu.getUUID() + "." + extName; File uploadedFile = new File(userfilepath + date + newfilename); if (!uploadedFile.exists()) { // 如果要写入的文件或目录不存在,那么试着创建要写入的目录,以便写入文件 uploadedFile.getParentFile().mkdirs(); } item.write(uploadedFile); mapList.put("fieldname", fieldName); mapList.put( "filename", fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.length())); mapList.put("extname", extName); mapList.put("filepath", userfilepath + date + newfilename); } } catch (Exception e) { e.printStackTrace(); } return mapList; }
protected File forceToFile(FileItem fileItem) throws IOException, ServletException { if (fileItem.isInMemory()) { String name = fileItem.getName(); if (null == name) { throw new IllegalArgumentException("FileItem has null name"); } // some browsers (IE, Chrome) pass an absolute filename, we just want the name of the file, no // paths name = name.replace('\\', '/'); if (name.length() > 2 && name.charAt(1) == ':') { name = name.substring(2); } name = new File(name).getName(); File tmpFile = File.createTempFile(name, null); try { fileItem.write(tmpFile); return tmpFile; } catch (Exception e) { throw new ServletException("Failed to persist uploaded file to disk", e); } } else { return ((DiskFileItem) fileItem).getStoreLocation(); } }
/** * Delete an uploaded file. * * @param request * @param response * @return FileItem * @throws IOException */ protected static FileItem removeUploadedFile( HttpServletRequest request, HttpServletResponse response) throws IOException { String parameter = request.getParameter(PARAM_REMOVE); FileItem item = findFileItem(getSessionFileItems(request), parameter); if (item != null) { getSessionFileItems(request).remove(item); renderXmlResponse(request, response, DELETED_TRUE); logger.debug( "UPLOAD-SERVLET (" + request.getSession().getId() + ") removeUploadedFile: " + parameter + " " + item.getName() + " " + item.getSize()); } else { renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND); logger.info( "UPLOAD-SERVLET (" + request.getSession().getId() + ") removeUploadedFile: " + parameter + " unable to delete file because it isn't in session."); } return item; }
/** * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the * given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a * multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the mutlipart POST data * to be sent via the {@link PostMethod} */ @SuppressWarnings("unchecked") private void handleMultipartPost( PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart( fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart( fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource( fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader( STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
/** * Get an uploaded file item. * * @param request * @param response * @throws IOException */ public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameter = request.getParameter(PARAM_SHOW); FileItem item = findFileItem(getSessionFileItems(request), parameter); if (item != null) { logger.debug( "UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " returning: " + item.getContentType() + ", " + item.getName() + ", " + item.getSize() + " bytes"); response.setContentType(item.getContentType()); copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream()); } else { logger.info( "UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " file isn't in session."); renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND); } }
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(); } }
@SuppressWarnings("null") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); // if (!isMultipart) { return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. // factory.setRepository(new File("d:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // System.out.println(empid); try { // out = response.getWriter( ); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); readBOM(file); break; } } RequestDispatcher ReqDis = request.getRequestDispatcher("afterBOM.jsp"); ReqDis.forward(request, response); } catch (Exception ex) { ex.printStackTrace(); RequestDispatcher ReqDis = request.getRequestDispatcher("Error.jsp"); ReqDis.forward(request, response); } }
@Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); ResourceBundle bundle = (ResourceBundle) session.getAttribute("bundle"); String jsonError = ""; ServletContext context = request.getSession().getServletContext(); response.setContentType("application/json"); try { if (ServletFileUpload.isMultipartContent(request)) { String fileName; String filePath; FileType.Type type; List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { fileName = new File(item.getName()).getName(); type = FileType.getType(fileName); if (type != null) { filePath = context.getRealPath(type.getPath()); SecureRandom random = new SecureRandom(); fileName = new BigInteger(130, random).toString(32) + FileType.parseFileFormat(fileName); item.write(new File(filePath + File.separator + fileName)); request .getSession() .setAttribute( "urlCat", ServerLocationUtils.getServerPath(request) + type.getPath() + "/" + fileName); LOG.debug("File uploaded successfully"); response .getWriter() .print( new JSONObject() .put( "success", UTF8.encoding(bundle.getString("notification.upload.file.success")))); } else { jsonError = UTF8.encoding(bundle.getString("notification.wrong.file.format")); } } } } else { jsonError = UTF8.encoding(bundle.getString("notification.request.error")); } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); jsonError = UTF8.encoding(bundle.getString("notification.upload.file.error")); } finally { if (!jsonError.isEmpty()) { response.getWriter().print(new JSONObject().put("error", jsonError)); } } }
/** * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { // Extract the relevant content from the POST'd form if (ServletFileUpload.isMultipartContent(req)) { Map<String, String> responseMap; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request String deploymentType = null; String version = null; String fileName = null; InputStream artifactContent = null; try { List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("deploymentType")) { // $NON-NLS-1$ deploymentType = item.getString(); } else if (item.getFieldName().equals("version")) { // $NON-NLS-1$ version = item.getString(); } } else { fileName = item.getName(); if (fileName != null) fileName = FilenameUtils.getName(fileName); artifactContent = item.getInputStream(); } } // Default version is 1.0 if (version == null || version.trim().length() == 0) { version = "1.0"; // $NON-NLS-1$ } // Now that the content has been extracted, process it (upload the artifact to the s-ramp // repo). responseMap = uploadArtifact(deploymentType, fileName, version, artifactContent); } catch (SrampAtomException e) { responseMap = new HashMap<String, String>(); responseMap.put("exception", "true"); // $NON-NLS-1$ //$NON-NLS-2$ responseMap.put("exception-message", e.getMessage()); // $NON-NLS-1$ responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); // $NON-NLS-1$ } catch (Throwable e) { responseMap = new HashMap<String, String>(); responseMap.put("exception", "true"); // $NON-NLS-1$ //$NON-NLS-2$ responseMap.put("exception-message", e.getMessage()); // $NON-NLS-1$ responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); // $NON-NLS-1$ } finally { IOUtils.closeQuietly(artifactContent); } writeToResponse(responseMap, response); } else { response.sendError( HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, Messages.i18n.format("DeploymentUploadServlet.ContentTypeInvalid")); // $NON-NLS-1$ } }