List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest request)
From source file:com.orinus.script.safe.jetty.SRequest.java
public boolean isMultipartContent() { return ServletFileUpload.isMultipartContent(req); }
From source file:com.ephesoft.dcma.gwt.foldermanager.server.UploadDownloadFilesServlet.java
private void uploadFile(HttpServletRequest req, String currentBatchUploadFolderName) throws IOException { File tempFile = null;// w w w. j a va2 s. c o m InputStream instream = null; OutputStream out = null; String uploadFileName = EMPTY_STRING; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); uploadFileName = EMPTY_STRING; String uploadFilePath = EMPTY_STRING; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { uploadFileName = item.getName(); if (uploadFileName != null) { uploadFileName = uploadFileName .substring(uploadFileName.lastIndexOf(File.separator) + 1); } uploadFilePath = currentBatchUploadFolderName + File.separator + uploadFileName; try { instream = item.getInputStream(); tempFile = new File(uploadFilePath); out = new FileOutputStream(tempFile); byte buf[] = new byte[1024]; int len = instream.read(buf); while (len > 0) { out.write(buf, 0, len); len = instream.read(buf); } } catch (FileNotFoundException e) { LOG.error(UNABLE_TO_CREATE_THE_UPLOAD_FOLDER_PLEASE_TRY_AGAIN); } catch (IOException e) { LOG.error(UNABLE_TO_READ_THE_FILE_PLEASE_TRY_AGAIN); } finally { if (out != null) { out.close(); } if (instream != null) { instream.close(); } } } } } catch (FileUploadException e) { LOG.error(UNABLE_TO_READ_THE_FORM_CONTENTS_PLEASE_TRY_AGAIN); } LOG.info(THE_CURRENT_UPLOAD_FOLDER_NAME_IS + currentBatchUploadFolderName); LOG.info(THE_NAME_OF_FILE_BEING_UPLOADED_IS + uploadFileName); } else { LOG.error(REQUEST_CONTENTS_TYPE_IS_NOT_SUPPORTED); } }
From source file:com.globalsight.everest.webapp.pagehandler.administration.users.UserImportHandler.java
/** * Upload the xml file to tmp folder/* w w w.ja va 2s .c o m*/ * * @param request */ private File uploadFile(HttpServletRequest request) { File f = null; try { String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight" + File.separator + "tmp"; boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024000); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (!item.isFormField()) { String filePath = item.getName(); if (filePath.contains(":")) { filePath = filePath.substring(filePath.indexOf(":") + 1); } String originalFilePath = filePath.replace("\\", File.separator).replace("/", File.separator); String fileName = tmpDir + File.separator + originalFilePath; f = new File(fileName); f.getParentFile().mkdirs(); item.write(f); } } } return f; } catch (Exception e) { logger.error("File upload failed.", e); return null; } }
From source file:net.hillsdon.reviki.web.pages.impl.DefaultPageImpl.java
public View attach(final PageReference page, final ConsumedPath path, final HttpServletRequest request, final HttpServletResponse response) throws Exception { if (!ServletFileUpload.isMultipartContent(request)) { throw new InvalidInputException("multipart request expected."); }/* ww w .jav a2s. c o m*/ List<FileItem> items = getFileItems(request); try { if (items.size() > 4) { throw new InvalidInputException("One file at a time."); } String attachmentName = null; Long baseRevision = null; String attachmentMessage = null; FileItem file = null; for (FileItem item : items) { if (PARAM_ATTACHMENT_NAME.equals(item.getFieldName())) { attachmentName = item.getString().trim(); } if (PARAM_BASE_REVISION.equals(item.getFieldName())) { baseRevision = RequestParameterReaders.getLong(item.getString().trim(), PARAM_BASE_REVISION); } if (PARAM_ATTACHMENT_MESSAGE.equals(item.getFieldName())) { attachmentMessage = item.getString().trim(); if (attachmentMessage.length() == 0) { attachmentMessage = null; } } if (!item.isFormField()) { file = item; } } if (baseRevision == null) { baseRevision = VersionedPageInfo.UNCOMMITTED; } if (file == null || file.getSize() == 0) { request.setAttribute("flash", ERROR_NO_FILE); return attachments(page, path, request, response); } else { InputStream in = file.getInputStream(); try { // get the page from store - needed to get content of the special // pages which were not saved yet PageInfo pageInfo = _store.get(page, -1); // IE sends the full file path. storeAttachment(pageInfo, attachmentName, baseRevision, attachmentMessage, FilenameUtils.getName(file.getName()), in); _store.expire(pageInfo); return new RedirectToPageView(_wikiUrls, page, "/attachments/"); } finally { IOUtils.closeQuietly(in); } } } finally { for (FileItem item : items) { item.delete(); } } }
From source file:com.bristle.javalib.net.http.MultiPartFormDataParamMap.java
/************************************************************************** * Parse the specified HTTP request, initializing the map, and calling * the specified callback (if not null) for each file (if any) in the * streamed HTTP request. /*ww w . j av a2 s .c om*/ * *@param request The HTTP request *@param callback The callback class *@throws FileUploadException When the request is badly formed. *@throws IOException When an I/O error occurs reading the request. *@throws Throwable When thrown by the callback. **************************************************************************/ public void parseRequestStream(HttpServletRequest request, FileItemStreamCallBack callback) throws FileUploadException, IOException, Throwable { if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String strParamName = fileItemStream.getFieldName(); InputStream streamIn = fileItemStream.openStream(); String strParamValue = Streams.asString(streamIn); put(strParamName, strParamValue); // Note: Can't do the following usefully. The Parameter // Map of the HTTP Request is effectively readonly. // This does not report an error, but is a no-op. // request.getParameterMap().put(strParamName, strParamValue); } else { if (callback != null) { callback.fullyProcessAFileItemStream(fileItemStream); } } } } else { putAll(request.getParameterMap()); } }
From source file:helma.servlet.AbstractServletClient.java
/** * Handle a request./*w w w. j a v a 2 s .com*/ * * @param request ... * @param response ... * * @throws ServletException ... * @throws IOException ... */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request)); try { // get the character encoding String encoding = request.getCharacterEncoding(); if (encoding == null) { // no encoding from request, use the application's charset encoding = getApplication().getCharset(); } // read cookies Cookie[] reqCookies = request.getCookies(); if (reqCookies != null) { for (int i = 0; i < reqCookies.length; i++) { try { // get Cookies String key = reqCookies[i].getName(); if (sessionCookieName.equals(key)) { reqtrans.setSession(reqCookies[i].getValue()); } reqtrans.setCookie(key, reqCookies[i]); } catch (Exception badCookie) { log("Error setting cookie", badCookie); } } } // get the cookie domain to use for this response, if any. String resCookieDomain = cookieDomain; if (resCookieDomain != null) { // check if cookieDomain is valid for this response. // (note: cookieDomain is guaranteed to be lower case) // check for x-forwarded-for header, fix for bug 443 String proxiedHost = request.getHeader("x-forwarded-host"); if (proxiedHost != null) { if (proxiedHost.toLowerCase().indexOf(resCookieDomain) == -1) { resCookieDomain = null; } } else { String host = (String) reqtrans.get("http_host"); // http_host is guaranteed to be lower case if (host != null && host.indexOf(resCookieDomain) == -1) { resCookieDomain = null; } } } // check if session cookie is present and valid, creating it if not. checkSessionCookie(request, response, reqtrans, resCookieDomain); // read and set http parameters parseParameters(request, reqtrans, encoding); // read file uploads List uploads = null; ServletRequestContext reqcx = new ServletRequestContext(request); if (ServletFileUpload.isMultipartContent(reqcx)) { // get session for upload progress monitoring UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans); try { uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding); } catch (Exception upx) { log("Error in file upload", upx); String message; boolean tooLarge = (upx instanceof FileUploadBase.SizeLimitExceededException); if (tooLarge) { message = "File upload size exceeds limit of " + uploadLimit + " kB"; } else { message = upx.getMessage(); if (message == null || message.length() == 0) { message = upx.toString(); } } if (uploadStatus != null) { uploadStatus.setError(message); } if (uploadSoftfail || uploadStatus != null) { reqtrans.set("helma_upload_error", message); } else { int errorCode = tooLarge ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE : HttpServletResponse.SC_INTERNAL_SERVER_ERROR; sendError(response, errorCode, "Error in file upload: " + message); return; } } } ResponseTrans restrans = getApplication().execute(reqtrans); // delete uploads if any if (uploads != null) { for (int i = 0; i < uploads.size(); i++) { ((FileItem) uploads.get(i)).delete(); } } // if the response was already written and committed by the application // we can skip this part and return if (response.isCommitted()) { return; } // set cookies if (restrans.countCookies() > 0) { CookieTrans[] resCookies = restrans.getCookies(); for (int i = 0; i < resCookies.length; i++) try { Cookie c = resCookies[i].getCookie("/", resCookieDomain); response.addCookie(c); } catch (Exception x) { getApplication().logEvent("Error adding cookie: " + x); } } // write response writeResponse(request, response, reqtrans, restrans); } catch (Exception x) { log("Exception in execute", x); try { if (debug) { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x); } else { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The server encountered an error while processing your request. " + "Please check back later."); } } catch (IOException iox) { log("Exception in sendError", iox); } } }
From source file:com.groupon.odo.Proxy.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)// w ww.j a v a 2s . com */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // create thread specific session data requestInformation.set(new RequestInformation()); History history = new History(); logOriginalRequestHistory("POST", request, history); try { PostMethod postMethodProxyRequest = new PostMethod( this.getProxyURL(request, history, Constants.REQUEST_TYPE_POST)); // Forward the request headers setProxyRequestHeaders(request, postMethodProxyRequest); // Check if this is a mulitpart (file upload) POST if (ServletFileUpload.isMultipartContent(request)) { logger.info("POST:: Multipart"); DiskFileItemFactory diskFactory = createDiskFactory(); HttpUtilities.handleMultipartPost(postMethodProxyRequest, request, diskFactory); } else { logger.info("POST:: Not Multipart"); HttpUtilities.handleStandardPost(postMethodProxyRequest, request, history); } // use body filter to filter paths this.cullPathsByBodyFilter(history); // Execute the proxy request this.executeProxyRequest(postMethodProxyRequest, request, response, history); } catch (Exception e) { // TODO log to history logger.info("ERROR: cannot execute request: {}", e.getMessage()); } }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Performs an HTTP POST request/*from w w w. ja v a 2 s. c o m*/ * * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} object passed * in by the servlet engine representing the * client request to be proxied * @param httpServletResponse The {@link javax.servlet.http.HttpServletResponse} object by which * we can send a proxied response to the client */ public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { // Create a standard POST request String contentType = httpServletRequest.getContentType(); String destinationUrl = this.getProxyURL(httpServletRequest); debug("POST Request URL: " + httpServletRequest.getRequestURL(), " Content Type: " + contentType, " Destination URL: " + destinationUrl); PostMethod postMethodProxyRequest = new PostMethod(destinationUrl); // Forward the request headers setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest); setProxyRequestCookies(httpServletRequest, postMethodProxyRequest); // Check if this is a mulitpart (file upload) POST if (ServletFileUpload.isMultipartContent(httpServletRequest)) { this.handleMultipartPost(postMethodProxyRequest, httpServletRequest); } else { if (contentType == null || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equals(contentType)) { this.handleStandardPost(postMethodProxyRequest, httpServletRequest); } else { this.handleContentPost(postMethodProxyRequest, httpServletRequest); } } // Execute the proxy request this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse); }
From source file:com.company.project.web.controller.FileUploadController.java
@RequestMapping(value = "/asyncUpload2", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseBody/* w w w. j a va2 s . co m*/ public ResponseEntity<String> asyncFileUpload2(HttpServletRequest request) throws Exception { MultipartHttpServletRequest mpr = (MultipartHttpServletRequest) request; if (request instanceof MultipartHttpServletRequest) { CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("fileUpload"); List<MultipartFile> fs = (List<MultipartFile>) mpr.getFiles("fileUpload"); System.out.println("f: " + f); for (String key : mpr.getParameterMap().keySet()) { System.out.println("Param Key: " + key + "\n Value: " + mpr.getParameterMap().get(key)); } for (String key : mpr.getMultiFileMap().keySet()) { System.out.println("xParam Key: " + key + "\n xValue: " + mpr.getMultiFileMap().get(key)); } } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); Map<String, Object> parameterMap = new HashMap<>(); Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields"); //if(request.getContentType().contains("multipart/form-data")){ if (ServletFileUpload.isMultipartContent(request)) { Map<String, Object> map = new HashMap<>(); List<FileItem> filefields = new ArrayList<>(); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { //contentType: "image/jpeg", isFormField: false, fileName: "Chrysanthemum.jpg" if (item.isFormField()) { formfields.put(item.getFieldName(), item.getString()); } else { filefields.add(item); } } parameterMap.put("filefields", filefields); } return new ResponseEntity<>("success", HttpStatus.OK); }
From source file:de.knurt.fam.core.model.config.FileUploadController.java
public ModelAndView getModelAndView() { ModelAndView result = null;//from w ww . j a v a 2 s. c om if (tr.getFilename().equalsIgnoreCase("get") && tr.getRequest().getMethod().equalsIgnoreCase("GET") && tr.getSuffix().equalsIgnoreCase("html")) { // initial call for the fileupload page (<iframe // src="get-fileupload.html" ...) tr.setTemplateFile("page_fileupload.html"); result = TemplateConfig.me().getResourceController().handleGetRequests(tr, response, tr.getRequest()); } else if (tr.getFilename().equalsIgnoreCase("put") && tr.getRequest().getMethod().equalsIgnoreCase("GET") && tr.getSuffix().equalsIgnoreCase("json")) { // requesting existing files JSONArray json = new JSONArray(); File[] existings = this.getExistingFileNames(); for (File existing : existings) { json.put(this.getJSONObject(existing)); } this.write(json); } else if (tr.getFilename().equalsIgnoreCase("delete") && (tr.getRequest().getMethod().equalsIgnoreCase("POST") || tr.getRequest().getMethod().equalsIgnoreCase("DELETE")) && tr.getSuffix().equalsIgnoreCase("json")) { // delete boolean succ = false; File fileToDelete = this.getExistingFile(tr.getRequest().getParameter("file")); if (fileToDelete != null) { succ = fileToDelete.delete(); } this.write(succ ? "true" : "false"); } else if (tr.getFilename().equalsIgnoreCase("download") && tr.getRequest().getMethod().equalsIgnoreCase("GET") && tr.getSuffix().equalsIgnoreCase("json")) { File fileToDownload = this.getExistingFile(tr.getRequest().getParameter("file")); if (fileToDownload != null) { // force "save as" in browser response.setHeader("Content-Disposition", "attachment; filename=" + fileToDownload.getName()); // it is a pdf response.setContentType(mftm.getContentType(fileToDownload)); ServletOutputStream outputStream = null; FileInputStream inputStream = null; try { outputStream = response.getOutputStream(); inputStream = new FileInputStream(fileToDownload); int nob = IOUtils.copy(inputStream, outputStream); if (nob < 1) FamLog.error("fail to download: " + fileToDownload.getAbsolutePath(), 201204181310l); } catch (IOException e) { FamLog.exception(e, 201204181302l); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } } else if (tr.getFilename().equalsIgnoreCase("put") && tr.getRequest().getMethod().equalsIgnoreCase("POST") && tr.getSuffix().equalsIgnoreCase("json") && ServletFileUpload.isMultipartContent(tr.getRequest())) { // insert JSONObject json_result = new JSONObject(); // Parse the request try { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(tr.getRequest()); this.setError(items); if (this.error == null) { // Process the uploaded items for (FileItem item : items) { if (!item.isFormField()) { File uploadedFile = null; File upload_dir = this.uploadDir; if (upload_dir != null) { uploadedFile = new File(upload_dir.getAbsolutePath() + File.separator + this.getNewFilename(item.getName())); } try { item.write(uploadedFile); json_result = this.getJSONObject(uploadedFile); } catch (Exception e) { FamLog.exception(e, 201204170945l); json_result.put("error", "unknown"); } } } } else { // ? error json_result.put("error", this.error); } } catch (FileUploadException e) { FamLog.exception(e, 201204170928l); try { json_result.put("error", "unknown"); } catch (JSONException e1) { FamLog.exception(e1, 201204171037l); } } catch (JSONException e) { FamLog.exception(e, 201204171036l); } JSONArray json_wrapper = new JSONArray(); json_wrapper.put(json_result); this.write(json_wrapper); } return result; }