/** 获取所有文本域 */ 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; }
/** * Basic constructor that takes the request object and saves it to be used by the subsequent * methods * * @param request * HttpServletRequest object originating from the user request. */ @SuppressWarnings("unchecked") public VariablesBase(HttpServletRequest request) { if (request == null) { // logging exception to obtain stack trace to pinpoint the cause log4j.warn("Creating a VariablesBase with a null request", new Exception()); this.session = new HttpSessionWrapper(); this.isMultipart = false; } else { this.session = request.getSession(true); this.httpRequest = request; this.isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request)); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); // factory.setSizeThreshold(yourMaxMemorySize); // factory.setRepositoryPath(yourTempDirectory); ServletFileUpload upload = new ServletFileUpload(factory); // upload.setSizeMax(yourMaxRequestSize); try { items = upload.parseRequest(request); } catch (Exception ex) { ex.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; }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request != null && ServletFileUpload.isMultipartContent(request)) { ServletRequestContext ctx = new ServletRequestContext(request); long requestSize = ctx.contentLength(); if (requestSize > maxSize) { throw new MaxUploadSizeExceededException(maxSize); } } return true; }
protected List parseRequest(ServletRequestContext requestContext) throws FileUploadException { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request return upload.parseRequest(requestContext); }
protected File uploadFile(HttpServletRequest request, String repoDir, HttpServletResponse response, String extension) throws FileUploadException { response.setContentType("text/html; charset=utf-8"); ServletRequestContext servletRequestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext); File uploadedFile = null; if (isMultipart) { try { // Create a new file upload handler List items = parseRequest(servletRequestContext); // Process the uploaded items for (Iterator iter = items.iterator(); iter.hasNext();) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String fileName = item.getName(); String fileExtension = fileName; fileExtension = fileExtension.toLowerCase(); if (extension != null && !fileExtension.endsWith(extension)) { throw new Exception(" Illegal file type. Only " + extension + " files can be uploaded"); } String fileNameOnly = getFileName(fileName); uploadedFile = new File(repoDir, fileNameOnly); item.write(uploadedFile); } } } catch (Exception e) { String msg = "File upload failed"; log.error(msg, e); throw new FileUploadException(msg, e); } } return uploadedFile; }
@Override public boolean isMultipart(HttpServletRequest request) { // support HTTP PUT operation String method = request.getMethod().toLowerCase(); if (S.neq("post", method) && S.neq("put", method)) { return false; } return FileUploadBase.isMultipartContent(new ServletRequestContext(request)); }
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; }
/** * @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; }
/** * * @param req * @param rpcRequest * @param service * @return * @throws Exception */ private Map<String, InputStream> getStreams(HttpServletRequest req, RpcRequest rpcRequest, HttpAction service) throws Exception { if (!FileUploadBase.isMultipartContent(new ServletRequestContext(req))) { return null; } int streamsNumber = getInputStreamsNumber(rpcRequest, service); boolean isResponseStreamed = service.isBinaryResponse(); FileItemIterator iter = (FileItemIterator) req.getAttribute(REQ_ATT_MULTIPART_ITERATOR); int count = 0; final Map<String, InputStream> map = new HashMap(); final File tempDirectory; if (streamsNumber > 1 || streamsNumber == 1 && isResponseStreamed) { tempDirectory = createTempUploadDirectory(); req.setAttribute(REQ_ATT_TEMPORARY_FOLDER, tempDirectory); } else { tempDirectory = null; } FileItemStream item = (FileItemStream) req.getAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM); long availableLength = RpcConfig.getInstance().getMaxRequestSize(); while (item != null) { count++; long maxLength = Math.min(availableLength, RpcConfig.getInstance().getMaxFileSize()); if (count < streamsNumber || isResponseStreamed) { // if response is streamed all inputstreams have to be readed first File file = new File(tempDirectory, item.getFieldName()); FileOutputStream fos = new FileOutputStream(file); try { Miscellaneous.pipeSynchronously(new LimitedLengthInputStream(item.openStream(), maxLength), fos); } catch (MaxLengthExceededException ex) { if (maxLength == RpcConfig.getInstance().getMaxFileSize()) { throw new MaxLengthExceededException("Upload part '" + item.getFieldName() + "' exceeds maximum length (" + RpcConfig.getInstance().getMaxFileSize() + " bytes)", RpcConfig.getInstance().getMaxFileSize()); } else { throw new MaxLengthExceededException("Request exceeds maximum length (" + RpcConfig.getInstance().getMaxRequestSize() + " bytes)", RpcConfig.getInstance().getMaxRequestSize()); } } map.put(item.getFieldName(), new MetaDataInputStream(new FileInputStream(file), item.getName(), item.getContentType(), file.length(), null)); availableLength -= file.length(); } else if (count == streamsNumber) { map.put(item.getFieldName(), new MetaDataInputStream(new LimitedLengthInputStream(item.openStream(), maxLength), item.getName(), item.getContentType(), null, null)); break; } req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item); if (iter.hasNext()) { item = iter.next(); } else { item = null; } } if (count != streamsNumber) { throw new IllegalArgumentException("Invalid multipart request received. Number of uploaded files (" + count + ") does not match expected (" + streamsNumber + ")"); } return map; }
/** * @param requestContext * @return * @throws FileUploadException */ private List parseRequest(ServletRequestContext requestContext) throws FileUploadException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); return upload.parseRequest(requestContext); }
public static List parseRequest(ServletRequestContext requestContext) throws FileUploadException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); return upload.parseRequest(requestContext); }
/** * Determine if given request is multipart. */ public static boolean isMultipart(final HttpServletRequest httpRequest) { // We're circumventing ServletFileUpload.isMultipartContent as some clients (nuget) use PUT for multipart uploads return FileUploadBase.isMultipartContent(new ServletRequestContext(httpRequest)); }
private void initializeMultiPart(PageContext pc, boolean scriptProteced) { // get temp directory Resource tempDir = ((ConfigImpl)pc.getConfig()).getTempDirectory(); Resource tempFile; // Create a new file upload handler final String encoding=getEncoding(); FileItemFactory factory = tempDir instanceof File? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD,(File)tempDir): new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest()); HttpServletRequest req = pc.getHttpServletRequest(); ServletRequestContext context = new ServletRequestContext(req) { public String getCharacterEncoding() { return encoding; } }; // Parse the request try { FileItemIterator iter = upload.getItemIterator(context); //byte[] value; InputStream is; ArrayList<URLItem> list=new ArrayList<URLItem>(); String fileName; while (iter.hasNext()) { FileItemStream item = iter.next(); is=IOUtil.toBufferedInputStream(item.openStream()); if (item.getContentType()==null || StringUtil.isEmpty(item.getName())) { list.add(new URLItem(item.getFieldName(),new String(IOUtil.toBytes(is),encoding),false)); } else { fileName=getFileName(); tempFile=tempDir.getRealResource(fileName); _fileItems.put(fileName, new Item(tempFile,item.getContentType(),item.getName(),item.getFieldName())); String value=tempFile.toString(); IOUtil.copy(is, tempFile,true); list.add(new URLItem(item.getFieldName(),value,false)); } } raw= list.toArray(new URLItem[list.size()]); fillDecoded(raw,encoding,scriptProteced,pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); } catch (Exception e) { //throw new PageRuntimeException(Caster.toPageException(e)); fillDecodedEL(new URLItem[0],encoding,scriptProteced,pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); initException=e; } }
private void initializeMultiPart(PageContext pc, boolean scriptProteced) { // get temp directory Resource tempDir = ((ConfigImpl)pc.getConfig()).getTempDirectory(); Resource tempFile; // Create a new file upload handler final String encoding=getEncoding(); FileItemFactory factory = tempDir instanceof File? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD,(File)tempDir): new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest()); HttpServletRequest req = pc.getHttpServletRequest(); ServletRequestContext context = new ServletRequestContext(req) { @Override public String getCharacterEncoding() { return encoding; } }; // Parse the request try { FileItemIterator iter = upload.getItemIterator(context); //byte[] value; InputStream is; ArrayList<URLItem> list=new ArrayList<URLItem>(); String fileName; while (iter.hasNext()) { FileItemStream item = iter.next(); is=IOUtil.toBufferedInputStream(item.openStream()); if (item.getContentType()==null || StringUtil.isEmpty(item.getName())) { list.add(new URLItem(item.getFieldName(),new String(IOUtil.toBytes(is),encoding),false)); } else { fileName=getFileName(); tempFile=tempDir.getRealResource(fileName); _fileItems.put(fileName, new Item(tempFile,item.getContentType(),item.getName(),item.getFieldName())); String value=tempFile.toString(); IOUtil.copy(is, tempFile,true); list.add(new URLItem(item.getFieldName(),value,false)); } } raw= list.toArray(new URLItem[list.size()]); fillDecoded(raw,encoding,scriptProteced,pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); } catch (Exception e) { //throw new PageRuntimeException(Caster.toPageException(e)); fillDecodedEL(new URLItem[0],encoding,scriptProteced,pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); initException=e; } }
public void processUpload(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String hasHotDeployment = (String) configContext.getAxisConfiguration().getParameterValue("hotdeployment"); String hasHotUpdate = (String) configContext.getAxisConfiguration().getParameterValue("hotupdate"); req.setAttribute("hotDeployment", (hasHotDeployment.equals("true")) ? "enabled" : "disabled"); req.setAttribute("hotUpdate", (hasHotUpdate.equals("true")) ? "enabled" : "disabled"); RequestContext reqContext = new ServletRequestContext(req); boolean isMultipart = ServletFileUpload.isMultipartContent(reqContext); if (isMultipart) { try { //Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); //Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(req); // Process the uploaded items Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String fileName = item.getName(); String fileExtesion = fileName; fileExtesion = fileExtesion.toLowerCase(); if (!(fileExtesion.endsWith(".jar") || fileExtesion.endsWith(".aar"))) { req.setAttribute("status", "failure"); req.setAttribute("cause", "Unsupported file type " + fileExtesion); } else { String fileNameOnly; if (fileName.indexOf("\\") < 0) { fileNameOnly = fileName.substring(fileName.lastIndexOf("/") + 1, fileName .length()); } else { fileNameOnly = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName .length()); } File uploadedFile = new File(serviceDir, fileNameOnly); item.write(uploadedFile); req.setAttribute("status", "success"); req.setAttribute("filename", fileNameOnly); } } } } catch (Exception e) { req.setAttribute("status", "failure"); req.setAttribute("cause", e.getMessage()); } } renderView("upload.jsp", req, res); }
protected void parseRequest(HttpServletRequest request) throws FileUploadFailedException, FileSizeLimitExceededException { fileItemsMap.set(new HashMap<String, ArrayList<FileItemData>>()); formFieldsMap.set(new HashMap<String, ArrayList<String>>()); ServletRequestContext servletRequestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext); Long totalFileSize = 0L; if (isMultipart) { List items; try { items = parseRequest(servletRequestContext); } catch (FileUploadException e) { String msg = "File upload failed"; log.error(msg, e); throw new FileUploadFailedException(msg, e); } boolean multiItems = false; if (items.size() > 1) { multiItems = true; } // Add the uploaded items to the corresponding maps. for (Iterator iter = items.iterator(); iter.hasNext();) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName().trim(); if (item.isFormField()) { if (formFieldsMap.get().get(fieldName) == null) { formFieldsMap.get().put(fieldName, new ArrayList<String>()); } try { formFieldsMap.get().get(fieldName).add(new String(item.get(), "UTF-8")); } catch (UnsupportedEncodingException ignore) { } } else { String fileName = item.getName(); if ((fileName == null || fileName.length() == 0) && multiItems) { continue; } if (fileItemsMap.get().get(fieldName) == null) { fileItemsMap.get().put(fieldName, new ArrayList<FileItemData>()); } totalFileSize += item.getSize(); if (totalFileSize < totalFileUploadSizeLimit) { fileItemsMap.get().get(fieldName).add(new FileItemData(item)); } else { throw new FileSizeLimitExceededException(getFileSizeLimit() / 1024 / 1024); } } } } }
public boolean execute(HttpServletRequest request, HttpServletResponse response) throws CarbonException, IOException { String axis2Repo = ServerConfiguration.getInstance(). getFirstProperty(ServerConfiguration.AXIS2_CONFIG_REPO_LOCATION); PrintWriter out = response.getWriter(); if (CarbonUtils.isURL(axis2Repo)) { out.write("<script type=\"text/javascript\">" + "alert('You are not permitted to upload services to URL repository " + axis2Repo + "');" + "</script>"); out.flush(); return false; } response.setContentType("text/html; charset=utf-8"); ServletRequestContext servletRequestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext); if (isMultipart) { try { // Create a new file upload handler List items = parseRequest(servletRequestContext); // Process the uploaded items for (Iterator iter = items.iterator(); iter.hasNext();) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String fileName = item.getName(); String fileExtension = fileName; fileExtension = fileExtension.toLowerCase(); // check whether extension is valid checkServiceFileExtensionValidity(fileExtension, ALLOWED_FILE_EXTENSIONS); String fileNameOnly = getFileName(fileName); File uploadedFile; if (fileExtension.endsWith(".dbs")) { String repo = configurationContext.getAxisConfiguration(). getRepository().getPath(); String finalFolderName; if (fileExtension.endsWith(".dbs")) { finalFolderName = "dataservices"; } else { throw new CarbonException( "File with extension " + fileExtension + " is not supported!"); } File servicesDir = new File(repo, finalFolderName); if (!servicesDir.exists()) { servicesDir.mkdir(); } uploadedFile = new File(servicesDir, fileNameOnly); item.write(uploadedFile); //TODO: fix them out.write("<script type=\"text/javascript\" src=\"../main/admin/js/main.js\"></script>"); out.write("<script type=\"text/javascript\">" + "alert('File uploaded successfully');" + "loadServiceListingPage();" + "</script>"); } } return true; } } catch (Exception e) { log.error("File upload failed", e); out.write("<script type=\"text/javascript\" src=\"../ds/extensions/core/js/data_service.js\"></script>"); out.write("<script type=\"text/javascript\">" + "alert('Service file upload FAILED. You will be redirected to file upload screen. Reason :" + e.getMessage().replaceFirst(",","") + "');" + "loadDBSFileUploadPage();"+ //available in data_service.js "</script>"); } } return false; }
/** * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> * compliant <code>multipart/form-data</code> stream. * * @param req The servlet request to be parsed. * * @return A list of <code>FileItem</code> instances parsed from the * request, in the order that they were transmitted. * * @throws FileUploadException if there are problems reading/parsing * the request or storing files. * * @deprecated 1.1 Use {@link ServletFileUpload#parseRequest(HttpServletRequest)} instead. */ @Deprecated public List<FileItem> parseRequest(HttpServletRequest req) throws FileUploadException { return parseRequest(new ServletRequestContext(req)); }