private void parseParams() { DiskFileItemFactory dff = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(dff); sfu.setSizeMax(this.maxSize); sfu.setHeaderEncoding(Uploader.ENCODEING); FileItemIterator fii = sfu.getItemIterator(this.request); while (fii.hasNext()) { FileItemStream item = fii.next(); // 普通参数存储 if (item.isFormField()) { this.params.put(item.getFieldName(), this.getParameterValue(item.openStream())); } else { // 只保留一个 if (this.inputStream == null) { this.inputStream = item.openStream(); this.originalName = item.getName(); return; } } } } catch (Exception e) { this.state = this.errorInfo.get("UNKNOWN"); } }
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); } }
/** * @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(); } }
/** * Start the Upload of the items * * @throws Exception */ public void upload() throws Exception { UserController uc = new UserController(null); user = uc.retrieve(getUser().getEmail()); HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream fis = iter.next(); InputStream stream = fis.openStream(); if (!fis.isFormField()) { title = fis.getName(); File tmp = createTmpFile(); try { writeInTmpFile(tmp, stream); Item item = uploadFile(tmp); if (item != null) itemList.add(item); } finally { stream.close(); FileUtils.deleteQuietly(tmp); } } } } }
@SuppressWarnings("unchecked") private void parseParams(HttpServletRequest req) { try { Map m = req.getParameterMap(); for (Object e0 : m.entrySet()) { Map.Entry<String, ?> e = (Map.Entry<String, ?>) e0; Object v = e.getValue(); String vs = v instanceof String[] ? StringUtils.join((String[]) v, "") : ObjectUtils.toString(v, ""); setString(e.getKey(), vs); } if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload upload = createFileUpload(); List<FileItem> fileItems = upload.parseRequest(req); for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { setString(fileItem.getFieldName(), fileItem.getString(Charsets.DEFAULT)); } else { put(fileItem.getFieldName(), fileItem); } } } } catch (Exception e) { throw new WebException(e); } }
private void upload(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("text/plain"); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { log.warning("Got a form field: " + item.getFieldName()); } else { log.warning( "Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); // You now have the filename (item.getName() and the // contents (which you can read from stream). Here we just // print them back out to the servlet output stream, but you // will probably want to do something more interesting (for // example, wrap them in a Blob and commit them to the // datastore). int len; byte[] buffer = new byte[8192]; while ((len = stream.read(buffer, 0, buffer.length)) != -1) { res.getOutputStream().write(buffer, 0, len); } } } } catch (Exception ex) { throw new ServletException(ex); } }
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()); } }
public void uploadBundle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DotDataException, FileUploadException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); @SuppressWarnings("unchecked") List<FileItem> items = (List<FileItem>) upload.parseRequest(request); InputStream bundle = items.get(0).getInputStream(); String bundleName = items.get(0).getName(); String bundlePath = ConfigUtils.getBundlePath() + File.separator; String bundleFolder = bundleName.substring(0, bundleName.indexOf(".tar.gz")); String endpointId = getUser().getUserId(); response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); PublishAuditStatus status; try { status = PublishAuditAPI.getInstance().updateAuditTable(endpointId, null, bundleFolder); // Write file on FS FileUtil.writeToFile(bundle, bundlePath + bundleName); if (!status.getStatus().equals(Status.PUBLISHING_BUNDLE)) { new Thread(new PublishThread(bundleName, null, endpointId, status)).start(); } out.print( "<html><head><script>isLoaded = true;</script></head><body><textarea>{'status':'success'}</textarea></body></html>"); } catch (DotPublisherException e) { // TODO Auto-generated catch block out.print( "<html><head><script>isLoaded = true;</script></head><body><textarea>{'status':'error'}</textarea></body></html>"); } }
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 model * @param mfile * @author 韩友军<*****@*****.**> * @since 2012-11-20下午12:57:08 */ @SuppressWarnings("unchecked") @RequestMapping(value = "/doCancelCardByExcel.html", method = RequestMethod.POST) public String doCancelCardByExcelAction(ModelMap model, HttpServletRequest request) { DiskFileItemFactory objDiskFileItemFactory = new DiskFileItemFactory(); objDiskFileItemFactory.setSizeThreshold(1024 * 1024); // 缓存 ServletFileUpload objServletFileUpload = new ServletFileUpload(objDiskFileItemFactory); try { List<FileItem> fileItems = objServletFileUpload.parseRequest(request); Iterator<FileItem> iterator = fileItems.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); if (!fileItem.isFormField()) { String strPath = this.context.getRealPath("/upload/"); File file = new File(strPath + new Date().getTime() + ".xls"); fileItem.write(file); String strFilePath = file.getPath(); Map<String, Object> mapData = cardBO.cancelCard(strFilePath); model.put("data", mapData); model.put("success", true); } } } catch (Exception e) { model.put("success", false); } return "card/do_cancel_card_by_excel.html"; }
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; } }
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; }
public void upload() throws Exception { boolean isMultipart = ServletFileUpload.isMultipartContent(this.request); if (!isMultipart) { this.state = this.errorInfo.get("NOFILE"); return; } DiskFileItemFactory dff = new DiskFileItemFactory(); String savePath = this.getFolder(this.savePath); dff.setRepository(new File(savePath)); try { ServletFileUpload sfu = new ServletFileUpload(dff); sfu.setSizeMax(this.maxSize * 1024); sfu.setHeaderEncoding("utf-8"); FileItemIterator fii = sfu.getItemIterator(this.request); while (fii.hasNext()) { FileItemStream fis = fii.next(); if (!fis.isFormField()) { this.originalName = fis.getName() .substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1); if (!this.checkFileType(this.originalName)) { this.state = this.errorInfo.get("TYPE"); continue; } this.fileName = this.getName(this.originalName); this.type = this.getFileExt(this.fileName); this.url = savePath + "/" + this.fileName; BufferedInputStream in = new BufferedInputStream(fis.openStream()); FileOutputStream out = new FileOutputStream(new File(this.getPhysicalPath(this.url))); BufferedOutputStream output = new BufferedOutputStream(out); Streams.copy(in, output, true); this.state = this.errorInfo.get("SUCCESS"); // UE中只会处理单张上传,完成后即退出 break; } else { String fname = fis.getFieldName(); // 只处理title,其余表单请自行处理 if (!fname.equals("pictitle")) { continue; } BufferedInputStream in = new BufferedInputStream(fis.openStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuffer result = new StringBuffer(); while (reader.ready()) { result.append((char) reader.read()); } this.title = new String(result.toString().getBytes(), "utf-8"); reader.close(); } } } catch (SizeLimitExceededException e) { this.state = this.errorInfo.get("SIZE"); } catch (InvalidContentTypeException e) { this.state = this.errorInfo.get("ENTYPE"); } catch (FileUploadException e) { this.state = this.errorInfo.get("REQUEST"); } catch (Exception e) { this.state = this.errorInfo.get("UNKNOWN"); } }
@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); } }
private List<FileItem> parseRequest(HttpServletRequest servletRequest, String saveDir) throws FileUploadException { DiskFileItemFactory fac = createDiskFileItemFactory(saveDir); ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); return upload.parseRequest(createRequestContext(servletRequest)); }
private static ServletFileUpload createFileUpload() { ServletFileUpload upload = new ServletFileUpload( new DiskFileItemFactory(IN_MEMORY_FILE_SIZE_THRESHOLD, new File(TMP_DIR))); upload.setSizeMax(MAX_UPLOAD_FILE_SIZE); return upload; }
@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; } }
/** * 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); } }
@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(); } }
void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException { try { ServletFileUpload upload = createUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { receive(item); } } if (tracker.isEmpty()) { String errorMessage = "No file upload data found in request"; tracker.setException(new Exception(errorMessage)); tracker.handleFailed(); response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage); } else { tracker.handleFinished(); } } catch (Exception exception) { Throwable cause = exception.getCause(); if (cause instanceof FileSizeLimitExceededException) { exception = (Exception) cause; } tracker.setException(exception); tracker.handleFailed(); int errorCode = exception instanceof FileSizeLimitExceededException ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE : HttpServletResponse.SC_INTERNAL_SERVER_ERROR; response.sendError(errorCode, exception.getMessage()); } }
/** * Parses the input stream. * * @param request the request * @param response the response * @return the byte array output stream * @throws ServletException the servlet exception * @throws IOException Signals that an I/O exception has occurred. */ public ByteArrayOutputStream parseInputStream( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); // Process the input stream int len; byte[] buffer = new byte[8192]; while ((len = stream.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, len); } int maxFileSize = 10 * (1024 * 1024); // 10 megs max if (out.size() > maxFileSize) { response.sendError( HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "Max allowed file size: 10 Mb"); } } } catch (Exception e) { e.printStackTrace(); } return out; }
@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); } }
@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------"); }
/** * @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$ } }
public MultipartFormBean getFileFromRequest(HttpServletRequest request) throws FileUploadException { try { if (encoding != null) request.setCharacterEncoding(encoding); } catch (UnsupportedEncodingException e1) { throw new FileUploadException("Upload file encoding not supported!"); } MultipartFormBean resultBean = new MultipartFormBean(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); upload.setFileSizeMax(maxSize); List items = upload.parseRequest(request); Map fields = new HashMap(); try { Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // parameter values check String fn = item.getFieldName(); if (fn.startsWith("l_")) { if (fields.keySet().contains(fn)) { String[] arr = (String[]) fields.get(fn); String[] newArr = new String[arr.length + 1]; for (int i = 0; i < arr.length; i++) newArr[i] = arr[i]; newArr[arr.length] = item.getString(); fields.put(fn, newArr); } else { fields.put(fn, new String[] {item.getString(encoding)}); } } else { fields.put(fn, item.getString(encoding)); } } else { String ext = getFileExt(item.getName()); if (ext == null) { fields.put(item.getFieldName(), null); continue; } if (!extIsAllowed(ext)) { throw new FileUploadException("Upload file format '" + ext + "' is not accepted!"); } resultBean.addFileItem(item); fields.put(item.getFieldName(), null); } } resultBean.setFields(fields); } catch (UnsupportedEncodingException e) { throw new FileUploadException("Upload file encoding not supported!"); } return resultBean; }
protected List<FileItem> parseMultipartRequest(HttpServletRequest request) { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); try { return upload.parseRequest(request); } catch (FileUploadException e) { throw new RuntimeException(e); } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("开始!" + fileName); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); try { String rootPath = request.getRealPath("/"); String filePath = rootPath + uploadPath; // 若该路径目录不存在,则创建 File f = new File(filePath); if (!f.exists()) { f.mkdirs(); } File f2 = new File(filePath + File.separator + fileName + ".jpg"); if (f2.exists()) { out.print("文件已存在"); } else { InputStream inputStream = request.getInputStream(); FileOutputStream outputStream = new FileOutputStream(f2); try { int formlength = request.getContentLength(); byte[] formcontent = new byte[formlength]; int totalread = 0; int nowread = 0; while (totalread < formlength) { nowread = inputStream.read(formcontent, totalread, formlength); totalread += nowread; } outputStream.write(formcontent); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); out.print("错误:" + e.getMessage()); } finally { outputStream.close(); inputStream.close(); } } } catch (IOException e) { e.printStackTrace(); out.print("错误:" + e.getMessage()); } finally { out.close(); } System.out.println("结束"); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ArrayList<String> array = new ArrayList<>(); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory fit = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fit); File savePath = null; try { List<FileItem> ft = upload.parseRequest(request); for (FileItem f : ft) { if (!f.isFormField()) { String n = new File(f.getName()).getName(); savePath = new File( request.getServletContext().getRealPath("/") + "images/" + System.currentTimeMillis() + "_" + n); f.write(savePath); array.add(savePath.getName()); } /** file upload ends */ /** Start Get data from <inputs> */ if (f.isFormField()) { String value = f.getString(); array.add(value); } } } catch (Exception e) { e.printStackTrace(); } } if (array.get(0).toString().equals("addHotelPic")) { model.pojo.HotelPictures hotel_pictures = new model.pojo.HotelPictures(); model.pojo.ActionStatus action_status = (model.pojo.ActionStatus) model.DbManager.getInstance().retrieveDataById(model.pojo.ActionStatus.class, 6); model.pojo.Hotel hotel = (model.pojo.Hotel) model.DbManager.getInstance() .retrieveDataById(model.pojo.Hotel.class, Integer.parseInt(array.get(1))); hotel_pictures.setActionStatus(action_status); hotel_pictures.setHotel(hotel); hotel_pictures.setUrl(array.get(2).toString()); model.DbManager.getInstance().saveData(hotel_pictures); } } catch (Exception e) { e.printStackTrace(); } }
/** * Utility method for parsing a multipart servlet request. This method returns an iterator of * FileItem objects that corresponds to the request. * * @param request The servlet request containing the multipart request. * @return Returns an iterator of FileItem objects the corresponds to the request. * @throws Exception Thrown if any problems occur while processing the request. */ protected static Iterator processMultipartRequest(HttpServletRequest request) throws Exception { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); upload.setSizeMax(Environment.getLongValue(Environment.PROP_FILE_MAX_FILE_SIZE)); return upload.parseRequest(request).iterator(); }
/** 上传ruleset */ public void upRuleset() throws Exception { /** * form中的enctype必须是multipart/... 组件提供方法检测form表单的enctype属性 在isMultipartContent方法中同时检测了是否是post提交 * 如果不是post提交则返回false */ if (ServletFileUpload.isMultipartContent(request)) { String RulePath = (String) application.getAttribute("Ruleset"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(RulePath + "tmp")); // 临时文件目录 // 内存最大占用 factory.setSizeThreshold(1024000); ServletFileUpload sfu = new ServletFileUpload(factory); // 单个文件最大值byte sfu.setFileSizeMax(102400000); // 所有上传文件的总和最大值byte sfu.setSizeMax(204800000); List<FileItem> items = null; try { items = sfu.parseRequest(request); } catch (SizeLimitExceededException e) { error("size limit exception!"); return; } catch (Exception e) { error("Exception:" + e.getMessage()); return; } Json j = new Json(1, "ok"); JsonObjectNode data = j.createData(); JsonArrayNode files = new JsonArrayNode("filename"); data.addChild(files); Iterator<FileItem> iter = (items == null) ? null : items.iterator(); while (iter != null && iter.hasNext()) { FileItem item = (FileItem) iter.next(); // 文件域 if (!item.isFormField()) { String fileName = item.getName(); int index = fileName.lastIndexOf("\\"); if (index < 0) index = 0; fileName = fileName.substring(index); if (!fileName.endsWith(".xml")) fileName += ".xml"; BufferedInputStream in = new BufferedInputStream(item.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(RulePath + fileName))); Streams.copy(in, out, true); files.addItem(new JsonLeafNode("", fileName)); } } echo(j.toString()); } else { error("enctype error!"); } }