/** 获取所有文本域 */ public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException { if (!saveDir.isDirectory()) { saveDir.mkdir(); } List<?> fileItems = null; RequestContext requestContext = new ServletRequestContext(request); if (FileUpload.isMultipartContent(requestContext)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(saveDir); factory.setSizeThreshold(fileSizeThreshold); ServletFileUpload upload = new ServletFileUpload(factory); fileItems = upload.parseRequest(request); } return fileItems; }
/** 获取所有文本域 */ public static List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException { if (!saveDir.isDirectory()) { saveDir.mkdir(); } List<?> fileItems = null; RequestContext requestContext = new ServletRequestContext(request); if (FileUpload.isMultipartContent(requestContext)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(saveDir); factory.setSizeThreshold(fileSizeThreshold); ServletFileUpload upload = new ServletFileUpload(factory); fileItems = upload.parseRequest(request); } return fileItems; }
/** * Determine an appropriate FileUpload instance for the given encoding. * <p>Default implementation returns the shared FileUpload instance * if the encoding matches, else creates a new FileUpload instance * with the same configuration other than the desired encoding. * @param encoding the character encoding to use * @return an appropriate FileUpload instance. */ protected FileUpload prepareFileUpload(String encoding) { FileUpload fileUpload = getFileUpload(); FileUpload actualFileUpload = fileUpload; // Use new temporary FileUpload instance if the request specifies // its own encoding that does not match the default encoding. if (encoding != null && !encoding.equals(fileUpload.getHeaderEncoding())) { actualFileUpload = newFileUpload(getFileItemFactory()); actualFileUpload.setSizeMax(fileUpload.getSizeMax()); actualFileUpload.setFileSizeMax(fileUpload.getFileSizeMax()); actualFileUpload.setHeaderEncoding(encoding); } return actualFileUpload; }
public List<FileItem> checkContentType(HttpServletRequest request, String encoding){ if(null != fileTypes && fileTypes.size() > 0){ FileUpload fileUpload = prepareFileUpload(encoding); try { List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request); for (FileItem item : fileItems) { if(!item.isFormField()) { //必须是文件 log.debug("client want to upload file with name: " + item.getName()); log.debug("client want to upload file with type: " + item.getContentType()); if (!fileTypes.contains(AppFileUtils.getFileExtByName(item.getName()))) { for(String fileType : fileTypes){ log.error("Allowd fileType is: "+fileType); } throw new NotAllowUploadFileTypeException("Not allow upload file type exception occur, client upload type is: "+AppFileUtils.getFileExtByName(item.getName())); } } } return fileItems; } catch (FileUploadException e) { throw new NotAllowUploadFileTypeException("Not allow upload file type exception occur... \r\n" + e.getMessage()); } } return null; }
public MultiPartEnabledRequest(HttpServletRequest req) { super(req); this.multipart = FileUpload.isMultipartContent(req); if (multipart) { try { readHttpParams(req); } catch (FileUploadException e) { Trace.write(Trace.Error,e, "MultiPartEnabledRequest"); e.printStackTrace(); } } }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AttachmentIsEmptyException * Thrown, when the attachment is of zero size. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws FileUploadException, IOException, AttachmentIsEmptyException, AuthorizationException { List<AttachmentResource> result = new ArrayList<>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.assertAttachmentSize(file.getContentType(), file.getSize(), false); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws MaxLengthReachedException * attachment size is to large * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AttachmentIsEmptyException * Thrown, when the attachment is of zero size. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws MaxLengthReachedException, FileUploadException, IOException, AttachmentIsEmptyException, AuthorizationException { List<AttachmentResource> result = new ArrayList<AttachmentResource>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.assertAttachmentSize(file.getContentType(), file.getSize(), false); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws MaxLengthReachedException * attachment size is to large * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws MaxLengthReachedException, FileUploadException, IOException, AuthorizationException { List<AttachmentResource> result = new ArrayList<AttachmentResource>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.assertAttachmentSize(file.getContentType(), file.getSize(), false); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws MaxLengthReachedException * attachment size is to large * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws MaxLengthReachedException, FileUploadException, IOException, AuthorizationException { List<AttachmentResource> result = new ArrayList<AttachmentResource>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.checkAttachmentSize(file); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
/** * respond to an HTTP POST request; only to handle the login process * * @param req * HttpServletRequest object with the client request * @param res * HttpServletResponse object back to the client * @exception ServletException * in case of difficulties * @exception IOException * in case of difficulties */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // catch the login helper posts String option = req.getPathInfo(); String[] parts = option.split("/"); if ((parts.length == 2) && ((parts[1].equals("login")))) { doLogin(req, res, null); } else if (FileUpload.isMultipartContent(req)) { setSession(req); postUpload(req, res); } else { sendError(res, HttpServletResponse.SC_NOT_FOUND); } }
/** * Retrieve the JBPM Process Designer deployment archive from the request * * @param request the request * @return the input stream onto the deployment archive * @throws WorkflowException * @throws FileUploadException * @throws IOException */ private InputStream getDeploymentArchive(HttpServletRequest request) throws FileUploadException, IOException { if (!FileUpload.isMultipartContent(request)) { throw new FileUploadException("Not a multipart request"); } GPDUpload fileUpload = new GPDUpload(); List list = fileUpload.parseRequest(request); Iterator iterator = list.iterator(); if (!iterator.hasNext()) { throw new FileUploadException("No process file in the request"); } FileItem fileItem = (FileItem) iterator.next(); if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) { throw new FileUploadException("Not a process archive"); } return fileItem.getInputStream(); }
/** * Handles a file contained in the specified {@code request}. If you use * FileUpload, please make sure to add the needed dependencies, i.e. * {@code commons-fileupload} and {@code servlet-api} (later will be removed * in a newer version of the {@code commons-fileupload}. * * @param request * the request to handle the file upload from * @param factory * the {@code FileItemFactory} used to handle the request * * @return the {@code List} of loaded files * * @throws FileUploadException * if the file upload fails */ public static List<FileItem> handleFileUpload(final HttpRequest request, final FileItemFactory factory) throws FileUploadException { final List<FileItem> items; if (request instanceof HttpEntityEnclosingRequest && "POST".equals(request.getRequestLine().getMethod())) { // create the ServletFileUpload final FileUpload upload = new FileUpload(factory); final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; items = upload.parseRequest(new RequestWrapper(entityRequest)); } else { items = new ArrayList<FileItem>(); } return items; }
/** * Determine an appropriate FileUpload instance for the given encoding. * <p>Default implementation returns the shared FileUpload instance * if the encoding matches, else creates a new FileUpload instance * with the same configuration other than the desired encoding. * @param encoding the character encoding to use * @return an appropriate FileUpload instance. */ protected FileUpload prepareFileUpload(String encoding) { FileUpload fileUpload = getFileUpload(); FileUpload actualFileUpload = fileUpload; // Use new temporary FileUpload instance if the request specifies // its own encoding that does not match the default encoding. if (encoding != null && !encoding.equals(fileUpload.getHeaderEncoding())) { actualFileUpload = newFileUpload(getFileItemFactory()); actualFileUpload.setSizeMax(fileUpload.getSizeMax()); actualFileUpload.setHeaderEncoding(encoding); } return actualFileUpload; }
@Override protected FileUpload newFileUpload(FileItemFactory fileItemFactory) { ServletFileUpload upload = new ServletFileUpload(fileItemFactory); upload.setSizeMax(-1); if (request != null) { // 注入监听 FileUploadProgressListener uploadProgressListener = new FileUploadProgressListener(); upload.setProgressListener(uploadProgressListener); request.getSession().setAttribute(C.UPLOAD_PROGRESS_LISTENER_KEY, uploadProgressListener); } return upload; }
@Override protected FileUpload newFileUpload(FileItemFactory fileItemFactory) { return new ServletFileUpload() { @Override public List<FileItem> parseRequest(HttpServletRequest request) { if (request instanceof MultipartHttpServletRequest) { throw new IllegalStateException("Already a multipart request"); } List<FileItem> fileItems = new ArrayList<FileItem>(); MockFileItem fileItem1 = new MockFileItem( "field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1"); MockFileItem fileItem1x = new MockFileItem( "field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1"); MockFileItem fileItem2 = new MockFileItem( "field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2"); MockFileItem fileItem2x = new MockFileItem( "field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2"); MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3"); MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4"); MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5"); fileItems.add(fileItem1); fileItems.add(fileItem1x); fileItems.add(fileItem2); fileItems.add(fileItem2x); fileItems.add(fileItem3); fileItems.add(fileItem4); fileItems.add(fileItem5); return fileItems; } }; }
protected Source getCenterSource(HttpServletRequest request){ PropertyTree dom = new PropertyTree(); dom.setProperty("/partnerships", ""); dom.setProperty("add_partnership/", ""); try { boolean isMultipart = FileUpload.isMultipartContent(request); if (isMultipart) { Hashtable ht = getHashtable(request); String partnershipId = null; if (((String) ht.get("request_action")).equalsIgnoreCase("change")) { partnershipId = (String) ht.get("selected_partnership_id"); } else { partnershipId = (String) ht.get("partnership_id"); modifyPartnership(ht, request, dom); } getSelectedPartnership(partnershipId, dom); } getAllPartnerships(dom); } catch (Exception e) { SFRMProcessor.getInstance().getLogger().debug("Unable to process the partnership page request", e); throw new RuntimeException("Unable to process the partnership page request", e); } return dom.getSource(); }
protected Source getCenterSource(HttpServletRequest request) { PropertyTree dom = new PropertyTree(); dom.setProperty("/partnerships", ""); dom.setProperty("add_partnership/", ""); try { boolean isMultipart = FileUpload.isMultipartContent(request); if (isMultipart) { Hashtable ht = getHashtable(request); String partnershipId = null; if (((String) ht.get("request_action")).equalsIgnoreCase("change")) { partnershipId = (String) ht.get("selected_partnership_id"); } else { partnershipId = (String) ht.get("partnership_id"); updatePartnership(ht, request, dom); } getSelectedPartnership(partnershipId, dom); } getAllPartnerships(dom); } catch (Exception e) { EbmsProcessor.core.log.debug("Unable to process the partnership page request", e); throw new RuntimeException("Unable to process the partnership page request", e); } return dom.getSource(); }
protected Source getCenterSource(HttpServletRequest request) { PropertyTree dom = new PropertyTree(); dom.setProperty("/partnerships", ""); dom.setProperty("add_partnership/", ""); try { boolean isMultipart = FileUpload.isMultipartContent(request); if (isMultipart) { Hashtable ht = getHashtable(request); String selectedPartnershipId = null; if (((String) ht.get("request_action")) .equalsIgnoreCase("change")) { selectedPartnershipId = (String) ht .get("selected_partnership_id"); } else { selectedPartnershipId = (String) ht.get("partnership_id"); updatePartnership(ht, request, dom); } getSelectedPartnership(selectedPartnershipId, dom); } getAllPartnerships(dom); } catch (Exception e) { AS2Processor.core.log.debug("Unable to process the partnership page request", e); throw new RuntimeException("Unable to process the partnership page request", e); } return dom.getSource(); }
protected Source getCenterSource(HttpServletRequest request) { PropertyTree dom = new PropertyTree(); dom.setProperty("/partnerships", ""); dom.setProperty("add_partnership/", ""); try { boolean isMultipart = FileUpload.isMultipartContent(request); if (isMultipart) { Hashtable ht = getHashtable(request); String selectedPartnershipId = null; if (((String) ht.get("request_action")) .equalsIgnoreCase("change")) { selectedPartnershipId = (String) ht .get("selected_partnership_id"); } else { selectedPartnershipId = (String) ht.get("partnership_id"); updatePartnership(ht, request, dom); } getSelectedPartnership(selectedPartnershipId, dom); } getAllPartnerships(dom); } catch (Exception e) { AS2PlusProcessor.getInstance().getLogger().debug("Unable to process the partnership page request", e); throw new RuntimeException("Unable to process the partnership page request", e); } return dom.getSource(); }
@Test public void blockingIOAdapterFunctionalTest() throws Exception { log.info("BLOCKING IO ADAPTER FUNCTIONAL TEST [ " + testCase.getDescription() + " ]"); if (log.isDebugEnabled()){ log.debug("Request body\n" + IOUtils.toString(testCase.getBodyInputStream())); } final FileUpload fileUpload = new FileUpload(); final FileItemIterator fileItemIterator = fileUpload.getItemIterator(testCase.getRequestContext()); try(final CloseableIterator<ParserToken> parts = Multipart.multipart(testCase.getMultipartContext()).forBlockingIO(testCase.getBodyInputStream())) { while (parts.hasNext()) { ParserToken parserToken = parts.next(); ParserToken.Type partItemType = parserToken.getType(); if (ParserToken.Type.NESTED_END.equals(partItemType) || ParserToken.Type.NESTED_START.equals(partItemType)) { // Commons file upload is not returning an item representing the start/end of a nested multipart. continue; } assertTrue(fileItemIterator.hasNext()); FileItemStream fileItemStream = fileItemIterator.next(); assertEquals(parserToken, fileItemStream); } } }
public static ClassifiableContentIF getFileUploadContent(HttpServletRequest request) { // Handle file upload String contentType = request.getHeader("content-type"); // out.write("CT: " + contentType + " " + tm + " " + id); if (contentType != null && contentType.startsWith("multipart/form-data")) { try { FileUpload upload = new FileUpload(new DefaultFileItemFactory()); for (FileItem item : upload.parseRequest(request)) { if (item.getSize() > 0) { // ISSUE: could make use of content type if known byte[] content = item.get(); ClassifiableContent cc = new ClassifiableContent(); String name = item.getName(); if (name != null) cc.setIdentifier("fileupload:name:" + name); else cc.setIdentifier("fileupload:field:" + item.getFieldName()); cc.setContent(content); return cc; } } } catch (Exception e) { throw new OntopiaRuntimeException(e); } } return null; }
public WsFileUploader( Path path, long maxMemorySize, long maxRequestSize, List<MediaProcessing> postprocessing ) { super( postprocessing ); log.info( "file uploader path = {}", path ); val factory = new DiskFileItemFactory(); factory.setSizeThreshold( ( int ) maxMemorySize ); factory.setRepository( path.toFile() ); upload = new FileUpload( factory ); upload.setSizeMax( maxRequestSize ); }
@Override protected FileUpload newFileUpload(FileItemFactory fileItemFactory) { return new ServletFileUpload() { @Override public List<FileItem> parseRequest(HttpServletRequest request) { if (request instanceof MultipartHttpServletRequest) { throw new IllegalStateException("Already a multipart request"); } List<FileItem> fileItems = new ArrayList<FileItem>(); MockFileItem fileItem1 = new MockFileItem( "field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1"); MockFileItem fileItem1x = new MockFileItem( "field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1"); MockFileItem fileItem2 = new MockFileItem( "field2", "type2", empty ? "" : "C:/field2.txt", empty ? "" : "text2"); MockFileItem fileItem2x = new MockFileItem( "field2x", "type2", empty ? "" : "C:\\field2x.txt", empty ? "" : "text2"); MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3"); MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4"); MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5"); fileItems.add(fileItem1); fileItems.add(fileItem1x); fileItems.add(fileItem2); fileItems.add(fileItem2x); fileItems.add(fileItem3); fileItems.add(fileItem4); fileItems.add(fileItem5); return fileItems; } }; }
protected Map<String, String[]> parseFileUpload() { //log.debug("parseFileUpload"); Map<String, String[]> parameters = new Hashtable<String, String[]>(); if (portletRequest instanceof HttpServletRequest) { HttpServletRequest hreq = (HttpServletRequest) portletRequest; //logRequestParameters(); //logRequestAttributes(); ServletRequestContext ctx = new ServletRequestContext(hreq); if (FileUpload.isMultipartContent(ctx)) { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { fileItems = upload.parseRequest(hreq); } catch (Exception e) { log.error("Unable to parse multi part form!!!", e); } if (fileItems != null) { //log.debug("File items has size " + fileItems.size()); for (int i = 0; i < fileItems.size(); i++) { FileItem item = (FileItem) fileItems.get(i); String[] tmpstr = new String[1]; if (item.isFormField()) { tmpstr[0] = item.getString(); } else { tmpstr[0] = "fileinput"; } //log.debug("File item " + item.getFieldName() + "->" + tmpstr[0]); parameters.put(item.getFieldName(), tmpstr); } } } } return parameters; }
protected void parseRequest(MultipartFormData multipartFormData, FileUpload fileUpload, RestMultipartRequestContext requestContext) { try { FileItemIterator itemIterator = fileUpload.getItemIterator(requestContext); while (itemIterator.hasNext()) { FileItemStream stream = itemIterator.next(); multipartFormData.addPart(new FormPart(stream)); } } catch (Exception e) { throw new RestException(Status.BAD_REQUEST, e, "multipart/form-data cannot be processed"); } }
@Override public void doFilter(HttpExchange exchange, Chain chain) throws IOException { final Map<String, List<String>> params = parseGetParameters(exchange); Map<String, Pair<String, File>> streams = null; if( HttpExchangeUtils.isPost(exchange) ) { if( HttpExchangeUtils.isMultipartContent(exchange) ) { streams = new HashMap<String, Pair<String, File>>(); try { FileItemIterator ii = new FileUpload().getItemIterator(new ExchangeRequestContext(exchange)); while( ii.hasNext() ) { final FileItemStream is = ii.next(); final String name = is.getFieldName(); try( InputStream stream = is.openStream() ) { if( !is.isFormField() ) { // IE passes through the full path of the file, // where as Firefox only passes through the // filename. We only need the filename, so // ensure that we string off anything that looks // like a path. final String filename = STRIP_PATH_FROM_FILENAME.matcher(is.getName()).replaceFirst( "$1"); final File tempfile = File.createTempFile("equella-manager-upload", "tmp"); tempfile.getParentFile().mkdirs(); streams.put(name, new Pair<String, File>(filename, tempfile)); try( OutputStream out = new BufferedOutputStream(new FileOutputStream(tempfile)) ) { ByteStreams.copy(stream, out); } } else { addParam(params, name, Streams.asString(stream)); } } } } catch( Exception t ) { throw new RuntimeException(t); } } else { try( InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), "UTF-8") ) { BufferedReader br = new BufferedReader(isr); String query = br.readLine(); parseQuery(query, params); } } } exchange.setAttribute(PARAMS_KEY, params); exchange.setAttribute(MULTIPART_STREAMS_KEY, streams); // attributes seem to last the life of a session... I don't know why... exchange.setAttribute("error", null); chain.doFilter(exchange); }
@Activate protected void activate(ComponentContext ctx) { this.fu = new FileUpload(); log.info(getClass() + " activated."); }
/** * @see http://www.oschina.net/code/snippet_698737_13402 * @param request * @return * @throws IOException */ public static Map<String, Object> uploadFiles(HttpServlet servlet, HttpServletRequest request) { Map<String, Object> map = JwUtils.newHashMap(); Map<String, String> fileMap = JwUtils.newHashMap(); map.put("file", fileMap); DiskFileItemFactory factory = new DiskFileItemFactory();// 创建工厂 factory.setSizeThreshold(1024 * 1024 * 30);// 设置最大缓冲区为30M // 设置缓冲区目录 String savePath = servlet.getServletContext().getRealPath("/WEB-INF/temp"); factory.setRepository(new File(savePath)); FileUpload upload = new FileUpload(factory);// 获得上传解析器 upload.setHeaderEncoding("UTF-8");// 解决上传文件名乱码 try { String targetFolderPath = servlet.getServletContext().getRealPath("/WEB-INF/" + ConfigUtils.getProperty("web.files.upload.folder")); File targetFolder = new File(targetFolderPath);// 目标文件夹 if(!targetFolder.exists()) { targetFolder.mkdir(); } List<FileItem> fileItems = upload.parseRequest(new ServletRequestContext(request));// 解析请求体 for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) {// 判断是普通表单项还是文件上传项 String name = fileItem.getFieldName();// 表单名 String value = fileItem.getString("UTF-8");// 表单值 map.put(name, value); } else {// 文件上传项 String fileName = fileItem.getName();// 获取文件名 if (StringUtils.isEmpty(fileName))// 判断是否上传了文件 continue; // 截取文件名 int index = fileName.lastIndexOf("/"); if (index > -1) { fileName = fileName.substring(index); } // 检查文件是否允许上传 index = fileName.lastIndexOf("."); if (index > -1 && index < fileName.length() - 1) { String ext = fileName.substring(index + 1).toLowerCase(); if (!ConfigUtils.getString("web.files.upload.extension").contains(";" + ext + ";")) { LOGGER.warn("The file {} is not allowed to upload.", fileName); continue; } } // 生成唯一文件名,保留原文件名 String newFileName = UUID.randomUUID().toString(); // 将文件内容写到服务器端 String targetPath = targetFolderPath + "/" + newFileName; File targetFile = new File(targetPath);// 目标文件 targetFile.createNewFile(); fileItem.write(targetFile); fileItem.delete();// 删除临时文件 fileMap.put(fileName, newFileName); } } } catch (Exception e) { e.printStackTrace(); } return map; }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log("Iniciar tramitaci�"); String xmlData = ""; String xmlConfig = ""; if (FileUpload.isMultipartContent(request)) { try { DiskFileUpload fileUpload = new DiskFileUpload(); List fileItems = fileUpload.parseRequest(request); for (int i = 0; i < fileItems.size(); i++) { FileItem fileItem = (FileItem) fileItems.get(i); if (fileItem.getFieldName().equals("xmlData")) { xmlData = fileItem.getString(); } if (fileItem.getFieldName().equals("xmlConfig")) { xmlConfig = fileItem.getString(); } } } catch (FileUploadException e) { throw new UnavailableException("Error uploading", 1); } } else { xmlData = request.getParameter("xmlData"); xmlConfig = request.getParameter("xmlConfig"); } log("XML Data: " + xmlData); log("XML Config: " + xmlConfig); log("Enviant dades a: " + urlTramitacio); String token = iniciarTramite(xmlData, xmlConfig); if (token == null) { log("Token �s null"); } else { log("Token: " + token); StringBuffer url = new StringBuffer(urlRedireccio); url.append(urlRedireccio.indexOf('?') == -1 ? '?' : '&'); url.append(tokenName); url.append('='); url.append(token); log("Redireccionant a: " + url.toString()); response.sendRedirect(response.encodeRedirectURL(url.toString())); } }
@Test public void writeMultipart() throws Exception { MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); parts.add("name 1", "value 1"); parts.add("name 2", "value 2+1"); parts.add("name 2", "value 2+2"); parts.add("name 3", null); Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg"); parts.add("logo", logo); // SPR-12108 Resource utf8 = new ClassPathResource("/org/springframework/http/converter/logo.jpg") { @Override public String getFilename() { return "Hall\u00F6le.jpg"; } }; parts.add("utf8", utf8); Source xml = new StreamSource(new StringReader("<root><child/></root>")); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.setContentType(MediaType.TEXT_XML); HttpEntity<Source> entity = new HttpEntity<Source>(xml, entityHeaders); parts.add("xml", entity); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); this.converter.setMultipartCharset(UTF_8); this.converter.write(parts, new MediaType("multipart", "form-data", UTF_8), outputMessage); final MediaType contentType = outputMessage.getHeaders().getContentType(); assertNotNull("No boundary found", contentType.getParameter("boundary")); // see if Commons FileUpload can read what we wrote FileItemFactory fileItemFactory = new DiskFileItemFactory(); FileUpload fileUpload = new FileUpload(fileItemFactory); RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage); List<FileItem> items = fileUpload.parseRequest(requestContext); assertEquals(6, items.size()); FileItem item = items.get(0); assertTrue(item.isFormField()); assertEquals("name 1", item.getFieldName()); assertEquals("value 1", item.getString()); item = items.get(1); assertTrue(item.isFormField()); assertEquals("name 2", item.getFieldName()); assertEquals("value 2+1", item.getString()); item = items.get(2); assertTrue(item.isFormField()); assertEquals("name 2", item.getFieldName()); assertEquals("value 2+2", item.getString()); item = items.get(3); assertFalse(item.isFormField()); assertEquals("logo", item.getFieldName()); assertEquals("logo.jpg", item.getName()); assertEquals("image/jpeg", item.getContentType()); assertEquals(logo.getFile().length(), item.getSize()); item = items.get(4); assertFalse(item.isFormField()); assertEquals("utf8", item.getFieldName()); assertEquals("Hall\u00F6le.jpg", item.getName()); assertEquals("image/jpeg", item.getContentType()); assertEquals(logo.getFile().length(), item.getSize()); item = items.get(5); assertEquals("xml", item.getFieldName()); assertEquals("text/xml", item.getContentType()); verify(outputMessage.getBody(), never()).close(); }
@Test public void writeMultipartOrder() throws Exception { MyBean myBean = new MyBean(); myBean.setString("foo"); MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); parts.add("part1", myBean); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.setContentType(MediaType.TEXT_XML); HttpEntity<MyBean> entity = new HttpEntity<MyBean>(myBean, entityHeaders); parts.add("part2", entity); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); this.converter.setMultipartCharset(UTF_8); this.converter.write(parts, new MediaType("multipart", "form-data", UTF_8), outputMessage); final MediaType contentType = outputMessage.getHeaders().getContentType(); assertNotNull("No boundary found", contentType.getParameter("boundary")); // see if Commons FileUpload can read what we wrote FileItemFactory fileItemFactory = new DiskFileItemFactory(); FileUpload fileUpload = new FileUpload(fileItemFactory); RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage); List<FileItem> items = fileUpload.parseRequest(requestContext); assertEquals(2, items.size()); FileItem item = items.get(0); assertTrue(item.isFormField()); assertEquals("part1", item.getFieldName()); assertEquals("{\"string\":\"foo\"}", item.getString()); item = items.get(1); assertTrue(item.isFormField()); assertEquals("part2", item.getFieldName()); // With developer builds we get: <MyBean><string>foo</string></MyBean> // But on CI server we get: <MyBean xmlns=""><string>foo</string></MyBean> // So... we make a compromise: assertThat(item.getString(), allOf(startsWith("<MyBean"), endsWith("><string>foo</string></MyBean>"))); }
@Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { Logger logger = MiscUtils.getLogger(); String simulationData = null; boolean simulationError = false; try { FileUpload upload = new FileUpload(new DefaultFileItemFactory()); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); for(FileItem item:items) { if(item.isFormField()) { String name = item.getFieldName(); if(name.equals("simulateError")) { simulationError=true; } } else { if(item.getFieldName().equals("simulateFile")) { InputStream is = item.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); simulationData = writer.toString(); } } } if(simulationData != null && simulationData.length()>0) { if(simulationError) { Driver.readResponseFromXML(request, simulationData); simulationData = (String)request.getAttribute("olisResponseContent"); request.getSession().setAttribute("errors",request.getAttribute("errors")); } request.getSession().setAttribute("olisResponseContent", simulationData); request.setAttribute("result", "File successfully uploaded"); } }catch(Exception e) { MiscUtils.getLogger().error("Error",e); } return mapping.findForward("success"); }