List of usage examples for org.apache.commons.fileupload FileItem getContentType
String getContentType();
null
if not defined. From source file:com.threecrickets.prudence.internal.lazy.LazyInitializationFile.java
/** * Creates a PHP-style item in the $_FILE map. * //from w w w .j a v a 2s.c om * @param fileItem * The file itme * @return A PHP-style $_FILE item */ private static Map<String, Object> createFileItemMap(FileItem fileItem) { Map<String, Object> exposedFileItem = new HashMap<String, Object>(); exposedFileItem.put("name", fileItem.getName()); exposedFileItem.put("type", fileItem.getContentType()); exposedFileItem.put("size", fileItem.getSize()); if (fileItem instanceof DiskFileItem) { DiskFileItem diskFileItem = (DiskFileItem) fileItem; exposedFileItem.put("tmp_name", diskFileItem.getStoreLocation().getAbsolutePath()); } // exposedFileItem.put("error", ); return exposedFileItem; }
From source file:com.google.caja.ancillary.servlet.UploadPage.java
static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Process the uploaded items List<ObjectConstructor> uploads = Lists.newArrayList(); if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); int maxUploadSizeBytes = 1 << 18; factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold factory.setRepository(new File("/dev/null")); // Do not store on disk ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxUploadSizeBytes); writeHeader(resp);//from w ww . j av a 2 s. c om // Parse the request List<?> items; try { items = upload.parseRequest(req); } catch (FileUploadException ex) { ex.printStackTrace(); resp.getWriter().write(Nodes.encode(ex.getMessage())); return; } for (Object fileItemObj : items) { FileItem item = (FileItem) fileItemObj; // Written for pre-generic java. if (!item.isFormField()) { // Then is a file FilePosition unk = FilePosition.UNKNOWN; String ct = item.getContentType(); uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i", StringLiteral.valueOf(unk, item.getString()), "ip", StringLiteral.valueOf(unk, item.getName()), "it", ct != null ? StringLiteral.valueOf(unk, ct) : null)); } } } else if (req.getParameter("url") != null) { List<URI> toFetch = Lists.newArrayList(); boolean failed = false; for (String value : req.getParameterValues("url")) { try { toFetch.add(new URI(value)); } catch (URISyntaxException ex) { if (!failed) { failed = true; resp.setStatus(500); resp.setContentType("text/html;charset=UTF-8"); } resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage())); } } if (failed) { return; } writeHeader(resp); FilePosition unk = FilePosition.UNKNOWN; for (URI uri : toFetch) { try { Content c = UriFetcher.fetch(uri); if (c.isText()) { uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i", StringLiteral.valueOf(unk, c.getText()), "ip", StringLiteral.valueOf(unk, uri.toString()), "it", StringLiteral.valueOf(unk, c.type.mimeType))); } } catch (IOException ex) { resp.getWriter() .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage())); } } } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().write("Content not multipart"); return; } Expression notifyParent = (Expression) QuasiBuilder.substV( "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads)); StringBuilder jsBuf = new StringBuilder(); RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true); notifyParent.render(rc); rc.getOut().noMoreTokens(); HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null)); Writer out = resp.getWriter(); out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString()))); }
From source file:edu.caltech.ipac.firefly.server.servlets.MultipartDataUtil.java
public static MultiPartData handleRequest(StringKey key, HttpServletRequest req) throws Exception { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest(req); MultiPartData data = new MultiPartData(key); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); data.addParam(name, value);//ww w.ja v a 2 s .c o m } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); File uf = new File(ServerContext.getTempWorkDir(), System.currentTimeMillis() + ".upload"); item.write(uf); data.addFile(fieldName, uf, fileName, contentType); StringKey fileKey = new StringKey(fileName, System.currentTimeMillis()); CacheManager.getCache(Cache.TYPE_TEMP_FILE).put(fileKey, uf); } } return data; }
From source file:com.liferay.apio.architect.internal.body.MultipartToBodyConverter.java
private static void _storeFileItem(FileItem fileItem, Consumer<String> valueConsumer, Consumer<BinaryFile> fileConsumer) { try {// w w w. j av a 2 s. c o m if (fileItem.isFormField()) { InputStream stream = fileItem.getInputStream(); valueConsumer.accept(Streams.asString(stream)); } else { BinaryFile binaryFile = new BinaryFile(fileItem.getInputStream(), fileItem.getSize(), fileItem.getContentType(), fileItem.getName()); fileConsumer.accept(binaryFile); } } catch (IOException ioe) { throw new BadRequestException("Invalid body", ioe); } }
From source file:jeeves.server.sources.ServiceRequestFactory.java
private static Element getMultipartParams(HttpServletRequest req, String uploadDir, int maxUploadSize) throws Exception { Element params = new Element("params"); DiskFileItemFactory fif = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(fif); sfu.setSizeMax(((long) maxUploadSize) * 1024L * 1024L); try {/*w w w . jav a2 s . co m*/ for (Object i : sfu.parseRequest(req)) { FileItem item = (FileItem) i; String name = item.getFieldName(); if (item.isFormField()) { String encoding = req.getCharacterEncoding(); params.addContent(new Element(name).setText(item.getString(encoding))); } else { String file = item.getName(); String type = item.getContentType(); long size = item.getSize(); if (Log.isDebugEnabled(Log.REQUEST)) Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size); //--- remove path information from file (some browsers put it, like IE) file = simplifyName(file); if (Log.isDebugEnabled(Log.REQUEST)) Log.debug(Log.REQUEST, "File is called " + file + " after simplification"); //--- we could get troubles if 2 users upload files with the same name item.write(new File(uploadDir, file)); Element elem = new Element(name).setAttribute("type", "file") .setAttribute("size", Long.toString(size)).setText(file); if (type != null) elem.setAttribute("content-type", type); if (Log.isDebugEnabled(Log.REQUEST)) Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem)); params.addContent(elem); } } } catch (FileUploadBase.SizeLimitExceededException e) { throw new FileUploadTooBigEx(); } return params; }
From source file:jeeves.server.sources.JeevletServiceRequestFactory.java
private static Element getMultipartParams(Request req, String uploadDir, int maxUploadSize) throws Exception { Element params = new Element("params"); // FIXME FileUpload - confirm only "multipart/form-data" entities must be parsed here ... // if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // The Apache FileUpload project parses HTTP requests which // conform to RFC 1867, "Form-based File Upload in HTML". That // is, if an HTTP request is submitted using the POST method, // and with a content type of "multipart/form-data", then // FileUpload can parse that request, and get all uploaded files // as FileItem. // 1/ Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240); // en mmoire factory.setRepository(new File(uploadDir)); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(factory); upload.setFileSizeMax(maxUploadSize * 1024 * 1024); List<FileItem> items;/*from w ww . ja va 2 s. c om*/ try { items = upload.parseRequest(req);// parseRepresentation(req.getEntity()); for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = (FileItem) it.next(); String name = item.getFieldName(); if (item.isFormField()) params.addContent(new Element(name).setText(item.getString())); else { String file = item.getName(); String type = item.getContentType(); long size = item.getSize(); Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size); //--- remove path information from file (some browsers put it, like IE) file = simplifyName(file); Log.debug(Log.REQUEST, "File is called " + file + " after simplification"); //--- we could get troubles if 2 users upload files with the same name item.write(new File(uploadDir, file)); Element elem = new Element(name).setAttribute("type", "file") .setAttribute("size", Long.toString(size)).setText(file); if (type != null) elem.setAttribute("content-type", type); Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem)); params.addContent(elem); } } } catch (FileUploadBase.FileSizeLimitExceededException e) { // throw jeeves exception --> reached code ? see apache docs - // FileUploadBase throw new FileUploadTooBigEx(); } catch (FileUploadException e) { // Sample Restlet ... " // The message of all thrown exception is sent back to client as simple plain text // response.setEntity(new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN)); // response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST); // e.printStackTrace(); // " ... now throw a JeevletException but // FIXME must throw Exception with a correct Status throw new JeevletException(e); } return params; }
From source file:com.aaasec.sigserv.csspserver.utility.SpServerLogic.java
public static String processFileUpload(HttpServletRequest request, HttpServletResponse response, RequestModel req) {/* ww w . java 2s. c om*/ // Create a factory for disk-based file items Map<String, String> paraMap = new HashMap<String, String>(); File uploadedFile = null; boolean uploaded = false; DiskFileItemFactory factory = new DiskFileItemFactory(); String uploadDirName = FileOps.getfileNameString(SpModel.getDataDir(), "uploads"); FileOps.createDir(uploadDirName); File storageDir = new File(uploadDirName); factory.setRepository(storageDir); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); paraMap.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName.length() > 0) { String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); uploadedFile = new File(storageDir, fileName); try { item.write(uploadedFile); uploaded = true; } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } } } } if (uploaded) { return SpServerLogic.getDocUploadResponse(req, uploadedFile); } else { if (paraMap.containsKey("xmlName")) { return SpServerLogic.getServerDocResponse(req, paraMap.get("xmlName")); } } } catch (FileUploadException ex) { LOG.log(Level.SEVERE, null, ex); } response.setStatus(HttpServletResponse.SC_NO_CONTENT); return ""; }
From source file:com.example.app.support.AppUtil.java
/** * Get the content type for a {@link FileItem} correcting it based on the file name if the browser didn't provide a * content type.// w ww .j a v a2 s . co m * * @param item the item * * @return the content type */ @Nonnull public static String getContentType(@Nonnull FileItem item) { String ct = item.getContentType(); if (ct == null || "application/octet-stream".equals(ct)) ct = MimeTypeUtility.getInstance().getContentType(item.getName()); // In case MimeTypeUtility doesn't do what we wish, it has no API contract. if (ct == null) ct = "application/octet-stream"; return ct; }
From source file:com.example.app.support.AppUtil.java
/** * Get the file extension for the given {@link FileItem}. * * @param file the file to retrieve the file extension for * * @return the file extension (example: "jpg") *//*from w w w.j av a 2 s . c om*/ @Nonnull public static String getExtension(FileItem file) { return _getExtensionWithFallback(file.getName(), file.getContentType()); }
From source file:beans.service.FileUploadTool.java
static public String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); DiskFileItemFactory factory = new DiskFileItemFactory(); int MaxMemorySize = 10000000; int MaxRequestSize = MaxMemorySize; String tmpDir = System.getProperty("TMP", "/tmp"); System.out.printf("temporary directory:%s", tmpDir); factory.setSizeThreshold(MaxMemorySize); factory.setRepository(new File(tmpDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MaxRequestSize);/* w w w . j ava 2 s .co m*/ // Parse the request try { List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) {//k -v String name = item.getFieldName(); String value = item.getString(); fields.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName == null || fileName.length() < 1) { return "file name is empty."; } String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName; System.out.printf("upload file:%s", localFileName); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File(localFileName); item.write(uploadedFile); filesOnServer.add(localFileName); } } return "success"; } catch (FileUploadException e) { e.printStackTrace(); return e.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } }