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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input type="text|radio|checkbox|etc", select, etc). String fieldname = item.getFieldName(); String fieldvalue = item.getString(); // ... (do your job here) } else { // Process form file field (input type="file"). String fieldname = item.getFieldName(); String filename = FilenameUtils.getName(item.getName()); InputStream filecontent = item.getInputStream(); // ... (do your job here) } } } catch (FileUploadException e) { throw new ServletException("Cannot parse multipart request.", e); } // ... }
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id_book = "", len = ""; // Imposto il content type della risposta e prendo l'output response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // La dimensione massima di ogni singolo file su system int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB // Dimensione massima della request int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB // Cartella temporanea File cartellaTemporanea = new File("C:\\tempo"); try { // Creo un factory per l'accesso al filesystem DiskFileItemFactory factory = new DiskFileItemFactory(); // Setto la dimensione massima di ogni file, opzionale factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte); // Setto la cartella temporanea, Opzionale factory.setRepository(cartellaTemporanea); // Istanzio la classe per l'upload ServletFileUpload upload = new ServletFileUpload(factory); // Setto la dimensione massima della request, opzionale upload.setSizeMax(dimensioneMassimaDellaRequestInByte); // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con // tutti i field sia di tipo file che gli altri List<FileItem> items = upload.parseRequest(request); /* * * Giro per tutti i campi inviati */ for (int i = 0; i < items.size(); i++) { FileItem item = items.get(i); // Controllo se si tratta di un campo di input normale if (item.isFormField()) { // Prendo solo il nome e il valore String name = item.getFieldName(); String value = item.getString(); if (name.equals("id_book")) { id_book = value; } if (name.equals("len")) { len = value; } } // Se si stratta invece di un file ho varie possibilità else { // Dopo aver ripreso tutti i dati disponibili String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); // scrivo direttamente su filesystem File uploadedFile = new File("/Users/Babol/Desktop/dVruhero/aMuseWebsite/web/userPhoto/" + fileName); // Solo se veramente ho inviato qualcosa if (item.getSize() > 0) { item.write(uploadedFile); DBconnection.EditCoverBook(fileName, Integer.parseInt(id_book)); } } } // out.println("</body>"); // out.println("</html>"); } catch (Exception ex) { System.out.println("Errore: " + ex.getMessage()); } finally { if (len.equals("ita")) response.sendRedirect("modify_book.jsp?id_book=" + id_book); else response.sendRedirect("modify_book_eng.jsp?id_book=" + id_book); } }
/** * Utility method to decode a multipart/fomr-data stream and return a Map of parameters of type * Object[], each of which can be a String or FileData. */ public static Map<String, Object[]> getParameterMapMultipart( PipelineContext pipelineContext, final ExternalContext.Request request, String headerEncoding) { final Map<String, Object[]> uploadParameterMap = new HashMap<String, Object[]>(); try { // Setup commons upload // Read properties // NOTE: We use properties scoped in the Request generator for historical reasons. Not too // good. int maxSize = RequestGenerator.getMaxSizeProperty(); int maxMemorySize = RequestGenerator.getMaxMemorySizeProperty(); final DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(maxMemorySize, SystemUtils.getTemporaryDirectory()); final ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory) { protected FileItem createItem(Map headers, boolean isFormField) throws FileUploadException { if (isFormField) { // Handle externalized values final String externalizeFormValuesPrefix = org.orbeon.oxf.properties.Properties.instance() .getPropertySet() .getString(ServletExternalContext.EXTERNALIZE_FORM_VALUES_PREFIX_PROPERTY); final String fieldName = getFieldName(headers); if (externalizeFormValuesPrefix != null && fieldName.startsWith(externalizeFormValuesPrefix)) { // In this case, we do as if the value content is an uploaded file so that it can // be externalized return super.createItem(headers, false); } else { // Just create the FileItem using the default way return super.createItem(headers, isFormField); } } else { // Just create the FileItem using the default way return super.createItem(headers, isFormField); } } }; upload.setHeaderEncoding(headerEncoding); upload.setSizeMax(maxSize); // Add a listener to destroy file items when the pipeline context is destroyed pipelineContext.addContextListener( new PipelineContext.ContextListenerAdapter() { public void contextDestroyed(boolean success) { for (final String name : uploadParameterMap.keySet()) { final Object values[] = uploadParameterMap.get(name); for (final Object currentValue : values) { if (currentValue instanceof FileItem) { final FileItem fileItem = (FileItem) currentValue; fileItem.delete(); } } } } }); // Wrap and implement just the required methods for the upload code final InputStream inputStream; try { inputStream = request.getInputStream(); } catch (IOException e) { throw new OXFException(e); } final RequestContext requestContext = new RequestContext() { public int getContentLength() { return request.getContentLength(); } public InputStream getInputStream() { // NOTE: The upload code does not actually check that it doesn't read more than the // content-length // sent by the client! Maybe here would be a good place to put an interceptor and make // sure we // don't read too much. return new InputStream() { public int read() throws IOException { return inputStream.read(); } }; } public String getContentType() { return request.getContentType(); } public String getCharacterEncoding() { return request.getCharacterEncoding(); } }; // Parse the request and add file information try { for (Object o : upload.parseRequest(requestContext)) { final FileItem fileItem = (FileItem) o; // Add value to existing values if any if (fileItem.isFormField()) { // Simple form field // Assume that form fields are in UTF-8. Can they have another encoding? If so, how is // it specified? StringUtils.addValueToObjectArrayMap( uploadParameterMap, fileItem.getFieldName(), fileItem.getString(STANDARD_PARAMETER_ENCODING)); } else { // File StringUtils.addValueToObjectArrayMap( uploadParameterMap, fileItem.getFieldName(), fileItem); } } } catch (FileUploadBase.SizeLimitExceededException e) { // Should we do something smart so we can use the Presentation // Server error page anyway? Right now, this is going to fail // miserably with an error. throw e; } catch (UnsupportedEncodingException e) { // Should not happen throw new OXFException(e); } finally { // Close the input stream; if we don't nobody does, and if this stream is // associated with a temporary file, that file may resist deletion if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new OXFException(e); } } } return uploadParameterMap; } catch (FileUploadException e) { throw new OXFException(e); } }