/** * Processes the FileItemStream as a Form Field. * * @param itemStream file item stream */ private void processFileItemStreamAsFormField(FileItemStream itemStream) { String fieldName = itemStream.getFieldName(); try { List<String> values; String fieldValue = Streams.asString(itemStream.openStream()); if (!parameters.containsKey(fieldName)) { values = new ArrayList<>(); parameters.put(fieldName, values); } else { values = parameters.get(fieldName); } values.add(fieldValue); } catch (IOException e) { LOG.warn("Failed to handle form field '{}'.", fieldName, e); } }
private Map<String, String> getRequestData(HttpServletRequest request) { Map<String, String> requestData = new HashMap<>(); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator itemIterator = upload.getItemIterator(request); while (itemIterator.hasNext()) { FileItemStream item = itemIterator.next(); InputStream itemStream = item.openStream(); String value = Streams.asString(itemStream, CharEncoding.UTF_8); requestData.put(item.getFieldName(), value); } } catch (FileUploadException | IOException e) { LOGGER.error("Failed to process request", e); } return requestData; }
/** * @param stream * The ServletFileUpload input stream * @param commonsConfigurator * Used to get the password for encryption */ public static String asString(InputStream stream, CommonsConfigurator commonsConfigurator) throws IOException { String value = Streams.asString(stream); if (isEncrypted(value, commonsConfigurator)) { try { value = StringUtils.substringAfter(value, Pbe.KAWANFW_ENCRYPTED); value = new Pbe().decryptFromHexa(value, CommonsConfiguratorCall.getEncryptionPassword(commonsConfigurator)); return value; } catch (Exception e) { String message = Tag.PRODUCT_USER_CONFIG_FAIL + " Impossible to decrypt the value " + value; message += ". Check that password values are the same on client and server side."; throw new IOException(message, e); } } else { return value; } }
public void parse(MultipartRequestCallback callback) throws IOException, FileUploadException, StatusServletException { if (!ServletFileUpload.isMultipartContent(request)) { LOGGER.error("Request content is not multipart."); throw new StatusServletException(Response.SC_PRECONDITION_FAILED); } final FileItemIterator iterator = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request); while (iterator.hasNext()) { // Gets the first HTTP request element. final FileItemStream item = iterator.next(); if (item.isFormField()) { final String value = Streams.asString(item.openStream(), "UTF-8"); properties.put(item.getFieldName(), value); } else if(callback != null) { callback.onInputStream(item.openStream(), item.getFieldName(), item.getContentType()); } } }
private String handleMultipart(RecordedRequest request) { RecordedUpload upload = new RecordedUpload(request); Exception exception; try { Map<String,String> params = new HashMap<>(); FileItemIterator iter = upload.getItemIterator(); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); System.out.println("Form field " + name + " with value " + value + " detected."); params.put(name,value); } else { System.out.println("File field " + name + " with file name " + item.getName() + " detected."); params.put(name, "file->"+item.getName()); } } return "Multipart:"+JSON.toJSONString(params); } catch (Exception e) { exception = e; } return "Multipart:error->"+exception; }
/** * Reads form values from the multipart request until a file is encountered. Field values are stored as strings for * retrieval using {@link #getFormFieldValue}. * @return True if there is an upload file available to read via {@link #getUploadFileItem()}. */ public boolean readFormData() { mUploadFileItem = null; try { while (mItemIterator.hasNext()) { FileItemStream lCurrentItem = mItemIterator.next(); /** * NOTE: the InputStream here is read here in a blocking way. Long upload hangs have been observed on live * environments at this point due to network issues. It should be possible to convert the stream to a * non-blocking stream at this point if required. */ InputStream lItemInputStream = lCurrentItem.openStream(); if (lCurrentItem.isFormField()) { //Read form values into the map String lParamName = lCurrentItem.getFieldName(); String lFieldValue = Streams.asString(lItemInputStream); mFieldParamMap.put(lParamName, lFieldValue); } else { //We've hit the file field, so stop the read for now mUploadFileItem = lCurrentItem; break; } lItemInputStream.close(); } } catch (IOException | FileUploadException e) { throw new ExInternal("Failed to read form data for the multipart request", e); } return mUploadFileItem != null; }
private void getFileItem(HttpServletRequest request) throws FileUploadException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { throw new IllegalArgumentException("Not multipart..."); } ServletFileUpload upload = new ServletFileUpload(); List<String> mdrEntries = new ArrayList<String>(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out.println("File field " + name + " with file name " + item.getName() + " detected."); // Process the input stream } String mdrEntry = handleInput(name, stream); mdrEntries.add(mdrEntry); } commitContent(mdrEntries); }
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { long gameId = 0l; String auth = null; try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(req); String json = ""; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); if ("gameId".equals(name)) gameId = Long.parseLong(value); if ("auth".equals(name)) auth = value; } else { json = Streams.asString(stream); } } res.setContentType("text/plain"); JSONObject jObject = new JSONObject(json); Object deserialized = JsonBeanDeserializer.deserialize(json); if (deserialized instanceof GamePackage && ((GamePackage) deserialized).getGame() != null) unpackGame((GamePackage) deserialized, req, auth); if (deserialized instanceof RunPackage && ((RunPackage) deserialized ).getRun() != null) unpackRun((RunPackage) deserialized, req, gameId, auth); } catch (Exception ex) { throw new ServletException(ex); } }
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp, OutputStream repoItemOutputStrem) throws IOException { log.debug("Multipart detected"); ServletFileUpload upload = new ServletFileUpload(); try { // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { // TODO What to do with this? log.debug("Form field {} with value {} detected.", name, Streams.asString(stream)); } else { // TODO Must we support multiple files uploading? log.debug("File field {} with file name detected.", name, item.getName()); log.debug("Start to receive bytes (estimated bytes)", Integer.toString(req.getContentLength())); int bytes = IOUtils.copy(stream, repoItemOutputStrem); resp.setStatus(SC_OK); log.debug("Bytes received: {}", Integer.toString(bytes)); } } } } catch (FileUploadException e) { throw new IOException(e); } }
private static MultipartRequest asMultipartRequest(HttpServletRequest request) throws Exception { String encoding = request.getCharacterEncoding(); MultipartRequest req = new MultipartRequest(request); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding(encoding); FileItemIterator it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream item = it.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); try { if (item.isFormField()) { req.setParameter(fieldName, Streams.asString(stream, encoding)); } else { String originalFilename = item.getName(); File diskFile = getTempFile(originalFilename); OutputStream fos = new FileOutputStream(diskFile); try { IoUtils.copy(stream, fos); } finally { IoUtils.closeQuietly(fos); } FilePart filePart = new FilePart(fieldName, originalFilename, diskFile); req.addFile(filePart); } } finally { IoUtils.closeQuietly(stream); } } return req; }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); try{ FileItemIterator iterator = upload.getItemIterator(request); if (iterator.hasNext()) { FileItemStream item = iterator.next(); String name = item.getFieldName(); logger.debug("Uploading file '{}' with item name '{}'", item.getName(), name); InputStream stream = item.openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); Streams.copy(stream, out, true); byte[] data = out.toByteArray(); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); response.getWriter().print(new String(data)); response.flushBuffer(); } else { logger.error("No file found in post request!"); throw new RuntimeException("No file found in post request!"); } } catch(Exception e){ logger.error("Unexpected error in FileUploadServlet.doPost: ", e); throw new RuntimeException(e); } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //CHECKSTYLE:ON ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iter = upload.getItemIterator(request); if (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); LOG.debug("Uploading file '{}' with item name '{}'", item.getName(), name); InputStream stream = item.openStream(); // Process the input stream ByteArrayOutputStream out = new ByteArrayOutputStream(); Streams.copy(stream, out, true); byte[] data = out.toByteArray(); cacheService.uploadedFile(name, data); } else { LOG.error("No file found in post request!"); throw new RuntimeException("No file found in post request!"); } } catch (Exception ex) { LOG.error("Unexpected error in FileUpload.doPost: ", ex); throw new RuntimeException(ex); } }
protected void internalImport( HttpServletRequest request, Properties options, long projectID ) throws Exception { String url = null; ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName().toLowerCase(); InputStream stream = item.openStream(); if (item.isFormField()) { if (name.equals("url")) { url = Streams.asString(stream); } else { options.put(name, Streams.asString(stream)); } } else { String fileName = item.getName().toLowerCase(); try { ProjectManager.getSingleton().importProject(projectID, stream, !fileName.endsWith(".tar")); } finally { stream.close(); } } } if (url != null && url.length() > 0) { internalImportURL(request, options, projectID, url); } }
@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); }
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { List<String> files = new ArrayList<>(); ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = null; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { LOGGER.debug("Form field " + name + " with value " + Streams.asString(stream) + " detected."); incrementStringsProcessed(); } else { LOGGER.debug("File field " + name + " with file name " + item.getName() + " detected."); // Process the input stream File tmpFile = File.createTempFile(UUID.randomUUID().toString() + "_MockUploadServlet", ".tmp"); tmpFile.deleteOnExit(); try (OutputStream os = new FileOutputStream(tmpFile)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = stream.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } incrementFilesProcessed(); files.add(tmpFile.getAbsolutePath()); } } } } } catch (FileUploadException e) { } try (Writer w = response.getWriter()) { w.write(Integer.toString(getFilesProcessed())); resetFilesProcessed(); resetStringsProcessed(); w.write("||"); w.write(files.toString()); } } else { try (Writer w = response.getWriter()) { w.write(Integer.toString(getFilesProcessed())); resetFilesProcessed(); resetStringsProcessed(); w.write("||"); } } }
/** * 파일을 Upload 처리한다. * * @param request * @param where * @param maxFileSize * @return * @throws Exception */ public static List<FormBasedFileVo> uploadFiles( HttpServletRequest request, String where, long maxFileSize) throws Exception { List<FormBasedFileVo> list = new ArrayList<FormBasedFileVo>(); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(maxFileSize); // SizeLimitExceededException // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { // System.out.println("Form field '" + name + "' with value '" + Streams.asString(stream) + // "' detected."); LOG.info("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected."); } else { // System.out.println("File field '" + name + "' with file name '" + item.getName() + "' detected."); LOG.info("File field '" + name + "' with file name '" + item.getName() + "' detected."); if ("".equals(item.getName())) { continue; } // Process the input stream FormBasedFileVo vo = new FormBasedFileVo(); String tmp = item.getName(); if (tmp.lastIndexOf("\\") >= 0) { tmp = tmp.substring(tmp.lastIndexOf("\\") + 1); } vo.setFileName(tmp); vo.setContentType(item.getContentType()); vo.setServerSubPath(getTodayString()); vo.setPhysicalName(getPhysicalFileName()); if (tmp.lastIndexOf(".") >= 0) { vo.setPhysicalName(vo.getPhysicalName() + tmp.substring(tmp.lastIndexOf("."))); } long size = saveFile(stream, new File(WebUtil.filePathBlackList(where) + SEPERATOR + vo.getServerSubPath() + SEPERATOR + vo.getPhysicalName())); vo.setSize(size); list.add(vo); } } } else { throw new IOException("form's 'enctype' attribute have to be 'multipart/form-data'"); } return list; }
/** * 파일을 Upload 처리한다. * * @param request * @param where * @param maxFileSize * @return * @throws Exception */ public static List<HeritFormBasedFileVO> uploadFiles(HttpServletRequest request, String where, long maxFileSize) throws Exception { List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>(); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(maxFileSize); // SizeLimitExceededException // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { //System.out.println("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected."); Logger.getLogger(HeritFormBasedFileUtil.class).info("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected."); } else { //System.out.println("File field '" + name + "' with file name '" + item.getName() + "' detected."); Logger.getLogger(HeritFormBasedFileUtil.class).info("File field '" + name + "' with file name '" + item.getName() + "' detected."); if ("".equals(item.getName())) { continue; } // Process the input stream HeritFormBasedFileVO vo = new HeritFormBasedFileVO(); String tmp = item.getName(); if (tmp.lastIndexOf("\\") >= 0) { tmp = tmp.substring(tmp.lastIndexOf("\\") + 1); } vo.setFileName(tmp); vo.setContentType(item.getContentType()); vo.setServerSubPath(getTodayString()); vo.setPhysicalName(getPhysicalFileName()); if (tmp.lastIndexOf(".") >= 0) { vo.setPhysicalName(vo.getPhysicalName() + tmp.substring(tmp.lastIndexOf("."))); } long size = saveFile(stream, new File(HeritWebUtil.filePathBlackList(where) + SEPERATOR + vo.getServerSubPath() + SEPERATOR + vo.getPhysicalName())); vo.setSize(size); list.add(vo); } } } else { throw new IOException("form's 'enctype' attribute have to be 'multipart/form-data'"); } return list; }
/** * 实现多文件的同时上传 */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("==========="); //设置接收的编码格式 request.setCharacterEncoding("UTF-8"); Date date = new Date();//获取当前时间 SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdfFolder = new SimpleDateFormat("yyMM"); // String newfileName = sdfFileName.format(date);//文件名称 String fileRealPath = "";//文件存放真实地址 String fileRealResistPath = "";//文件存放真实相对路径 //名称 界面编码 必须 和request 保存一致..否则乱码 String name = request.getParameter("name"); String id = request.getParameter("id"); //内容的ID,必须先添加内容,然后才能上传图片 // String newfileName = name; String firstFileName=""; // 获得容器中上传文件夹所在的物理路径 String savePath = this.getServletConfig().getServletContext().getRealPath("/") + "upload\\" + id +"\\"; System.out.println("路径" + savePath+"; name:"+name); File file = new File(savePath); if (!file.isDirectory()) { file.mkdirs(); } try { DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("UTF-8"); // upload.setFileItemFactory(factory) System.out.println("request:="+request); // 获取多个上传文件 List fileList = fileList = upload.parseRequest(request); System.out.println("fileList:"+fileList); // 遍历上传文件写入磁盘 Iterator it = fileList.iterator(); while (it.hasNext()) { Object obit = it.next(); if(obit instanceof DiskFileItem){ System.out.println("xxxxxxxxxxxxx"); DiskFileItem item = (DiskFileItem) obit; // 如果item是文件上传表单域 // 获得文件名及路径 String fileName = item.getName(); if (fileName != null) { firstFileName=item.getName().substring(item.getName().lastIndexOf("\\")+1); String formatName = firstFileName.substring(firstFileName.lastIndexOf("."));//获取文件后缀名 fileRealPath = savePath + fileName;//+ formatName;//文件存放真实地址 BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 获得文件输入流 BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(fileRealPath)));// 获得文件输出流 Streams.copy(in, outStream, true);// 开始把文件写到你指定的上传文件夹 //上传成功,则插入数据库 if (new File(fileRealPath).exists()) { //虚拟路径赋值 fileRealResistPath=sdfFolder.format(date)+"/"+fileRealPath.substring(fileRealPath.lastIndexOf("\\")+1); //保存到数据库 System.out.println("保存到数据库:"); System.out.println("name:"+name); System.out.println("虚拟路径:"+fileRealResistPath); } } } } } catch (org.apache.commons.fileupload.FileUploadException ex) { ex.printStackTrace(); System.out.println("没有上传文件"); return; } response.getWriter().write("1"); }
private void getFileItem(HttpServletRequest request, File root) throws FileUploadException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { throw new IllegalArgumentException("Not multipart..."); } ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); String fileName = null; String path = null; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); System.out.println("Name=" + item.getName()); if (item.isFormField()) { String value = Streams.asString(stream); System.out.println("FormField " + name + "=" + value); if (name.equals("name")) { fileName = value; } if (name.equals("path")) { path = value; } } else { System.out.println("File field " + name + " with file name " + item.getName() + " detected."); File output = new File(root, path + "/" + fileName); System.out.println("Write upload to " + output.getPath()); IOUtil.copyCompletely(stream, new FileOutputStream(output)); } } }
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { Long runId = null; String account = null; String serverPath = null; boolean last = false; ServletFileUpload upload = new ServletFileUpload(); res.setContentType("text/plain"); FileItemIterator iterator = upload.getItemIterator(req); System.out.println("before while"); while (iterator.hasNext()) { System.out.println("in while"); FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { if ("runId".equals(item.getFieldName())) { runId = Long.parseLong(Streams.asString(stream)); System.out.println("runid is " + runId); } if ("account".equals(item.getFieldName())) { account = Streams.asString(stream); System.out.println("account is " + account); } if ("last".equals(item.getFieldName())) { last = Boolean.parseBoolean(Streams.asString(stream)); System.out.println("last is " + last); } if ("serverPath".equals(item.getFieldName())) { serverPath = Streams.asString(stream); System.out.println("serverPath is " + serverPath); } } else { log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); AppEngineFile file = storeBlob(item.getContentType(), item.getName(), stream, last, serverPath); BlobKey blobkey = fileService.getBlobKey(file); if (blobkey != null) { // File exists BlobKey oldkey = FilePathManager.getBlobKey(account, runId, item.getName()); if (oldkey != null) { FilePathManager.delete(oldkey); blobstoreService.delete(oldkey); } FilePathManager.addFile(runId, account, item.getName(), blobkey); System.out.println(blobkey.toString()); } res.getWriter().write(file.getFullPath()); // else { // blobkey.toString(); // } } } } catch (Exception ex) { throw new ServletException(ex); } }
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { Long runId = null; String account = null; ServletFileUpload upload = new ServletFileUpload(); res.setContentType("text/plain"); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { if ("runId".equals(item.getFieldName())) { runId = Long.parseLong(Streams.asString(stream)); } if ("account".equals(item.getFieldName())) { account = Streams.asString(stream); } } else { BlobKey blobkey = storeBlob(item.getContentType(), item.getName(), stream); if (blobkey != null) { System.out.println(blobkey); // File exists BlobKey oldkey = FilePathManager.getBlobKey(account, runId, item.getName()); if (oldkey != null) { FilePathManager.delete(oldkey); blobstoreService.delete(oldkey); } FilePathManager.addFile(runId, account, item.getName(), blobkey); } else { blobkey.toString(); } } } } catch (Exception ex) { throw new ServletException(ex); } }
private HttpServletRequest processMultipartContent(final HttpServletRequest request) throws Exception { if (!ServletFileUpload.isMultipartContent(request)) return request; final Map<String, String> requestParams = new HashMap<>(); List<FileItemStream> listFiles = new ArrayList<>(); ServletFileUpload servletFileUpload = new ServletFileUpload(); String characterEncoding = request.getCharacterEncoding(); if (characterEncoding == null) { characterEncoding = "UTF-8"; } servletFileUpload.setHeaderEncoding(characterEncoding); FileItemIterator targets = servletFileUpload.getItemIterator(request); while (targets.hasNext()) { final FileItemStream item = targets.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { requestParams.put(name, Streams.asString(stream, characterEncoding)); } else { String fileName = item.getName(); if (fileName != null && !fileName.trim().isEmpty()) { ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); final byte[] bs = os.toByteArray(); stream.close(); listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{FileItemStream.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (OPEN_STREAM.equals(method.getName())) { return new ByteArrayInputStream(bs); } return method.invoke(item, args); } })); } } } request.setAttribute(FileItemStream.class.getName(), listFiles); return (HttpServletRequest) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{HttpServletRequest.class}, new InvocationHandler() { @Override public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable { if (GET_PARAMETER.equals(arg1.getName())) { return requestParams.get(arg2[0]); } return arg1.invoke(request, arg2); } }); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //log.info("Request:" + path); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart){ ServletFileUpload upload = new ServletFileUpload(); String user = request.getParameter("user"); String dir = request.getParameter("dir"); String path = request.getParameter("path"); String client = request.getRemoteAddr().replace('.', '_'); Map<String, String> meta = new HashMap<String, String>(); String archivePath = null; try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { InputStream stream = item.openStream(); if(item.getFieldName().equals("user")){ user = Streams.asString(stream); }else if(item.getFieldName().equals("dir")){ dir = Streams.asString(stream); }else if(item.getFieldName().equals("path")){ path = Streams.asString(stream); }else if(item.getFieldName().startsWith("meta_")) { meta.put(item.getFieldName(), Streams.asString(stream)); } stream.close(); } else if(!item.getName().equals("")) { archivePath = getArchivePath(user, dir, path); processUploadedFile(item, archivePath, client, meta); //request.setAttribute("message", "Update ok!"); response.setHeader("upload_status", "ok"); response.setHeader("archive_path", archivePath); } } } catch (Exception e) { //request.setAttribute("message", "Failed to uploading file, error:" + e.toString()); response.setHeader("upload_status", e.toString()); log.error(e.toString(), e); } }else { log.warn("The request is not a multpart content type."); } doGet(request, response); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //log.info("Request:" + path); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart){ ServletFileUpload upload = new ServletFileUpload(); String name = request.getParameter("name"); String path = request.getParameter("path"); String client = request.getRemoteAddr().replace('.', '_'); Map<String, String> meta = new HashMap<String, String>(); String archivePath = null; try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { InputStream stream = item.openStream(); if(item.getFieldName().equals("name")){ name = Streams.asString(stream); }else if(item.getFieldName().equals("path")){ path = Streams.asString(stream); }else if(item.getFieldName().startsWith("meta_")) { meta.put(item.getFieldName(), Streams.asString(stream)); } stream.close(); } else if(!item.getName().equals("")) { archivePath = getArchivePath(name, path); processUploadedFile(item, archivePath, client, meta); //request.setAttribute("message", "Update ok!"); response.setHeader("upload_status", "ok"); response.setHeader("archive_path", archivePath); response.setHeader("uuid", "ok"); } } } catch (Exception e) { //request.setAttribute("message", "Failed to uploading file, error:" + e.toString()); response.setHeader("upload_status", e.toString()); log.error(e.toString(), e); } }else { log.warn("The request is not a multpart content type."); } doGet(request, response); }
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ClientRequestIF clientRequest = (ClientRequestIF)req.getAttribute(ClientConstants.CLIENTREQUEST); // capture the session id boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { // TODO Change exception type String msg = "The HTTP Request must contain multipart content."; throw new RuntimeException(msg); } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); try { // Parse the request FileItemIterator iter = upload.getItemIterator(req); String fileName = null; String extension = null; InputStream stream = null; String uploadPath = null; while(iter.hasNext()) { FileItemStream item = iter.next(); InputStream input = item.openStream(); if(item.isFormField() && item.getFieldName().equals(WEB_FILE_UPLOAD_PATH_FIELD_NAME)) { uploadPath = Streams.asString(input); } else if (!item.isFormField()) { String fullName = item.getName(); int extensionInd = fullName.lastIndexOf("."); fileName = fullName.substring(0, extensionInd); extension = fullName.substring(extensionInd + 1); stream = input; } } if (stream != null) { clientRequest.newFile(uploadPath, fileName, extension, stream); } } catch (FileUploadException e) { throw new FileWriteExceptionDTO(e.getLocalizedMessage()); } }
@Post("multi") public Representation submitJob(Representation formRep) { RestletFileUpload upload = new RestletFileUpload() ; ComputationJob job = new ComputationJob() ; boolean inIframe = false ; try { FileItemIterator items = upload.getItemIterator(formRep) ; List<ParameterValue> values = new ArrayList<ParameterValue>() ; job.setParameterValues(values) ; State state = State.TITLE ; while (items.hasNext()) { FileItemStream item = items.next() ; InputStream itemStream = item.openStream() ; switch (state) { case TITLE: job.setTitle(Streams.asString(itemStream)) ; state = State.DESC ; break ; case DESC: job.setDescription(Streams.asString(itemStream)) ; state = State.COMMENTS ; break ; case COMMENTS: job.setComment(Streams.asString(itemStream)) ; state = State.PARAMS ; break ; case PARAMS: if (item.getFieldName().equals("iframe")) { inIframe = Boolean.parseBoolean(Streams.asString(itemStream)) ; } else { Parameter param = new Parameter() ; param.setName(parseParamName(item.getFieldName())) ; ParameterValue value = new ParameterValue() ; if (item.isFormField()) { value.setValue(Streams.asString(itemStream)) ; } else { value.setValue(storeFile(item.getName(), itemStream).getSource()) ; } value.setJob(job) ; value.setParameter(param) ; param.setValue(value) ; values.add(value) ; } break ; } } } catch (Exception e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Exception processing submit job form: " + e.getMessage(), e) ; } job = addNewJob(job) ; ComputationJob startedJob = startJob(job) ; if (inIframe) { return new StringRepresentation(buildIframeResponse(job), MediaType.TEXT_HTML) ; } else { Reference jobRef = getNamespace().jobRef(entryName, modelName,getResolver().getJobName(startedJob.getId()), true) ; redirectSeeOther(jobRef) ; return new StringRepresentation("Job submitted, URL: " + jobRef.toString() + ".") ; } }
@Override public String getName() { return Streams.checkFileName(fileName); }
/** * <p>Reads <code>body-data</code> from the current * <code>encapsulation</code> and writes its contents into the * output <code>Stream</code>. * <p> * <p>Arbitrary large amounts of data can be processed by this * method using a constant size buffer. (see {@link * #MultipartStream(InputStream, byte[], int, * MultipartStreamCopy.ProgressNotifier) constructor}). * * @param output The <code>Stream</code> to write data into. May * be null, in which case this method is equivalent * to {@link #discardBodyData()}. * @return the amount of data written. * @throws MalformedStreamException if the stream ends unexpectedly. * @throws IOException if an i/o error occurs. */ public int readBodyData(OutputStream output) throws MalformedStreamException, IOException { final InputStream istream = newInputStream(); return (int) Streams.copy(istream, output, false); }
/** * Returns the original filename in the client's filesystem. * * @return The original filename in the client's filesystem. * @throws org.apache.commons.fileupload.InvalidFileNameException The file name contains a NUL character, * which might be an indicator of a security attack. If you intend to * use the file name anyways, catch the exception and use * {@link org.apache.commons.fileupload.InvalidFileNameException#getName()}. */ public String getName() { return Streams.checkFileName(fileName); }
/** * <p>Reads <code>body-data</code> from the current * <code>encapsulation</code> and writes its contents into the * output <code>Stream</code>. * * <p>Arbitrary large amounts of data can be processed by this * method using a constant size buffer. (see {@link * #MultipartStream(InputStream,byte[],int, * MultipartStream.ProgressNotifier) constructor}). * * @param output The <code>Stream</code> to write data into. May * be null, in which case this method is equivalent * to {@link #discardBodyData()}. * * @return the amount of data written. * * @throws MalformedStreamException if the stream ends unexpectedly. * @throws IOException if an i/o error occurs. */ public int readBodyData(OutputStream output) throws MalformedStreamException, IOException { final InputStream istream = newInputStream(); return (int) Streams.copy(istream, output, false); }
/** * Returns the items file name. * * @return File name, if known, or null. * @throws InvalidFileNameException The file name contains a NUL character, * which might be an indicator of a security attack. If you intend to * use the file name anyways, catch the exception and use * InvalidFileNameException#getName(). */ public String getName() { return Streams.checkFileName(name); }
public InterceptingHTTPServletRequest(HttpServletRequest request) throws FileUploadException, IOException { super(request); allParameters = new Vector<Parameter>(); allParameterNames = new Vector<String>(); /* * Get all the regular parameters. */ Enumeration e = request.getParameterNames(); while(e.hasMoreElements()) { String param = (String)e.nextElement(); allParameters.add(new Parameter(param,request.getParameter(param),false)); allParameterNames.add(param); } /* * Get all the multipart fields. */ isMultipart = ServletFileUpload.isMultipartContent(request); if ( isMultipart ) { requestBody = new RandomAccessFile( File.createTempFile("oew","mpc"), "rw"); byte buffer[] = new byte[CHUNKED_BUFFER_SIZE]; long size = 0; int len = 0; while ( len != -1 && size <= Integer.MAX_VALUE) { len = request.getInputStream().read(buffer, 0, CHUNKED_BUFFER_SIZE); if ( len != -1 ) { size += len; requestBody.write(buffer,0,len); } } is = new RAFInputStream(requestBody); ServletFileUpload sfu = new ServletFileUpload(); FileItemIterator iter = sfu.getItemIterator(this); while(iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); /* * If this is a regular form field, add it to our * parameter collection. */ if (item.isFormField()) { String value = Streams.asString(stream); allParameters.add(new Parameter(name,value,true)); allParameterNames.add(name); } else { /* * This is a multipart content that is not a * regular form field. Nothing to do here. */ } } requestBody.seek(0); } }
/** * <p>Reads <code>body-data</code> from the current * <code>encapsulation</code> and writes its contents into the * output <code>Stream</code>. * * <p>Arbitrary large amounts of data can be processed by this * method using a constant size buffer. (see {@link * #MultipartStream(InputStream,byte[],int, ProgressNotifier) constructor}). * * @param output The <code>Stream</code> to write data into. May * be null, in which case this method is equivalent * to {@link #discardBodyData()}. * * @return the amount of data written. * * @throws MalformedStreamException if the stream ends unexpectedly. * @throws IOException if an i/o error occurs. */ public int readBodyData(OutputStream output) throws MalformedStreamException, IOException { final InputStream istream = newInputStream(); return (int) Streams.copy(istream, output, false); }
private byte[] readFileAndProperties(final HttpServletRequest request, final Map<String, String> properties) throws FileUploadException, IOException { byte[] data = null; final ServletFileUpload fileUpload = new ServletFileUpload(); final FileItemIterator iterator = fileUpload.getItemIterator(request); // Iterating on the fields sent into the request while (iterator.hasNext()) { final FileItemStream item = iterator.next(); final String name = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) { final String value = Streams.asString(stream); LOG.debug("field '" + name + "' = '" + value + '\''); // The current field is a property properties.put(name, value); } else { // The current field is a file LOG.debug("field '" + name + "' (FILE)"); final ByteArrayOutputStream serializedData = new ByteArrayOutputStream(); long dataSize = 0L; int b = stream.read(); while (b != -1 && dataSize < MAXIMUM_FILE_SIZE) { serializedData.write(b); dataSize++; b = stream.read(); } stream.close(); data = serializedData.toByteArray(); } } return data; }