Java Code Examples for javax.servlet.http.Part#getSubmittedFileName()
The following examples show how to use
javax.servlet.http.Part#getSubmittedFileName() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 8 votes |
/** * Extracts the file payload from an HttpServletRequest, checks that the file extension * is supported and uploads the file to Google Cloud Storage. */ public String getImageUrl(HttpServletRequest req, HttpServletResponse resp, final String bucket) throws IOException, ServletException { Part filePart = req.getPart("file"); final String fileName = filePart.getSubmittedFileName(); String imageUrl = req.getParameter("imageUrl"); // Check extension of file if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) { final String extension = fileName.substring(fileName.lastIndexOf('.') + 1); String[] allowedExt = {"jpg", "jpeg", "png", "gif"}; for (String s : allowedExt) { if (extension.equals(s)) { return this.uploadFile(filePart, bucket); } } throw new ServletException("file must be an image"); } return imageUrl; }
Example 2
Source File: TestVertxServerResponseToHttpServletResponse.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void prepareSendPartHeader_update(@Mocked Part part) { new Expectations() { { part.getContentType(); result = "type"; part.getSubmittedFileName(); result = "测 试"; } }; DownloadUtils.prepareDownloadHeader(response, part); Assert.assertTrue(serverResponse.isChunked()); Assert.assertEquals("type", response.getHeader(HttpHeaders.CONTENT_TYPE)); Assert.assertEquals( "attachment;filename=%E6%B5%8B%20%20%20%20%20%E8%AF%95;filename*=utf-8''%E6%B5%8B%20%20%20%20%20%E8%AF%95", response.getHeader(HttpHeaders.CONTENT_DISPOSITION)); }
Example 3
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 6 votes |
/** * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME * environment variable, appending a timestamp to end of the uploaded filename. */ @SuppressWarnings("deprecation") public String uploadFile(Part filePart, final String bucketName) throws IOException { DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = filePart.getSubmittedFileName() + dtString; // the inputstream is closed by default, so we don't need to close it here BlobInfo blobInfo = storage.create( BlobInfo .newBuilder(bucketName, fileName) // Modify access list to allow all users with link to read file .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))) .build(), filePart.getInputStream()); // return the public download link return blobInfo.getMediaLink(); }
Example 4
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 6 votes |
/** * Extracts the file payload from an HttpServletRequest, checks that the file extension * is supported and uploads the file to Google Cloud Storage. */ public String getImageUrl(HttpServletRequest req, HttpServletResponse resp, final String bucket) throws IOException, ServletException { Part filePart = req.getPart("file"); final String fileName = filePart.getSubmittedFileName(); String imageUrl = req.getParameter("imageUrl"); // Check extension of file if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) { final String extension = fileName.substring(fileName.lastIndexOf('.') + 1); String[] allowedExt = {"jpg", "jpeg", "png", "gif"}; for (String s : allowedExt) { if (extension.equals(s)) { return this.uploadFile(filePart, bucket); } } throw new ServletException("file must be an image"); } return imageUrl; }
Example 5
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 6 votes |
/** * Extracts the file payload from an HttpServletRequest, checks that the file extension * is supported and uploads the file to Google Cloud Storage. */ public String getImageUrl(HttpServletRequest req, HttpServletResponse resp, final String bucket) throws IOException, ServletException { Part filePart = req.getPart("file"); final String fileName = filePart.getSubmittedFileName(); String imageUrl = req.getParameter("imageUrl"); // Check extension of file if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) { final String extension = fileName.substring(fileName.lastIndexOf('.') + 1); String[] allowedExt = {"jpg", "jpeg", "png", "gif"}; for (String s : allowedExt) { if (extension.equals(s)) { return this.uploadFile(filePart, bucket); } } throw new ServletException("file must be an image"); } return imageUrl; }
Example 6
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 6 votes |
/** * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME * environment variable, appending a timestamp to end of the uploaded filename. */ @SuppressWarnings("deprecation") public String uploadFile(Part filePart, final String bucketName) throws IOException { DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = filePart.getSubmittedFileName() + dtString; // the inputstream is closed by default, so we don't need to close it here BlobInfo blobInfo = storage.create( BlobInfo .newBuilder(bucketName, fileName) // Modify access list to allow all users with link to read file .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))) .build(), filePart.getInputStream()); logger.log( Level.INFO, "Uploaded file {0} as {1}", new Object[]{ filePart.getSubmittedFileName(), fileName}); // return the public download link return blobInfo.getMediaLink(); }
Example 7
Source File: GeneratorController.java From packagedrone with Eclipse Public License 1.0 | 6 votes |
@RequestMapping ( value = "/generators/p2.category/channel/{channelId}/createCategoryXml", method = RequestMethod.POST ) public ModelAndView createCategoryXmlPost ( @PathVariable ( "channelId" ) final String channelId, final @RequestParameter ( "file" ) Part file, final BindingResult result ) throws Exception { if ( result.hasErrors () ) { final ModelAndView mav = new ModelAndView ( "createCategoryXml" ); mav.put ( "generators", this.generators.getInformations ().values () ); mav.put ( "channelId", channelId ); return mav; } final String name = file.getSubmittedFileName (); this.service.accessRun ( By.id ( channelId ), ModifiableChannel.class, channel -> { channel.getContext ().createGeneratorArtifact ( CategoryXmlGenerator.ID, file.getInputStream (), name, null ); } ); return redirectViewChannel ( channelId ); }
Example 8
Source File: UploadHelper.java From HongsCORE with MIT License | 6 votes |
/** * 检查上传对象并写入目标目录 * @param part * @param subn * @return * @throws Wrong */ public File upload(Part part, String subn) throws Wrong { if (part == null) { setResultName("", null); return null; } /** * 从上传项中获取类型并提取扩展名 */ String type = part.getContentType( /**/ ); type = getTypeByMime( type ); String extn = part.getSubmittedFileName(); extn = getExtnByName( extn ); try { return upload(part.getInputStream(), type, extn, subn); } catch ( IOException ex) { throw new Wrong(ex, "fore.form.upload.failed"); } }
Example 9
Source File: SolrRequestParsers.java From lucene-solr with Apache License 2.0 | 6 votes |
@Override public SolrParams parseParamsAndFillStreams( final HttpServletRequest req, ArrayList<ContentStream> streams) throws Exception { if (!isMultipart(req)) { throw new SolrException( ErrorCode.BAD_REQUEST, "Not multipart content! "+req.getContentType() ); } // Magic way to tell Jetty dynamically we want multi-part processing. "Request" here is a Jetty class req.setAttribute(Request.MULTIPART_CONFIG_ELEMENT, multipartConfigElement); MultiMapSolrParams params = parseQueryString( req.getQueryString() ); // IMPORTANT: the Parts will all have the delete() method called by cleanupMultipartFiles() for (Part part : req.getParts()) { if (part.getSubmittedFileName() == null) { // thus a form field and not file upload // If it's a form field, put it in our parameter map String partAsString = org.apache.commons.io.IOUtils.toString(new PartContentStream(part).getReader()); MultiMapSolrParams.addParam( part.getName().trim(), partAsString, params.getMap() ); } else { // file upload streams.add(new PartContentStream(part)); } } return params; }
Example 10
Source File: MCRUploadViaFormServlet.java From mycore with GNU General Public License v3.0 | 6 votes |
private void handleUploadedFile(MCRUploadHandler handler, Part file) throws Exception { String submitted = file.getSubmittedFileName(); if (submitted == null || "".equals(submitted)) { return; } try (InputStream in = file.getInputStream()) { String path = MCRUploadHelper.getFileName(submitted); if (requireDecompressZip(path)) { handleZipFile(handler, in); } else { handleUploadedFile(handler, file.getSize(), path, in); } } }
Example 11
Source File: TestRestClientRequestImpl.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void fileBoundaryInfo_validSubmittedFileName(@Mocked Part part) { new Expectations() { { part.getSubmittedFileName(); result = "a.txt"; part.getContentType(); result = MediaType.TEXT_PLAIN; } }; RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null); Buffer buffer = restClientRequest.fileBoundaryInfo("boundary", "name", part); Assert.assertEquals("\r\n" + "--boundary\r\n" + "Content-Disposition: form-data; name=\"name\"; filename=\"a.txt\"\r\n" + "Content-Type: text/plain\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n", buffer.toString()); }
Example 12
Source File: TestRestClientRequestImpl.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void fileBoundaryInfo_nullSubmittedFileName(@Mocked Part part) { new Expectations() { { part.getSubmittedFileName(); result = null; part.getContentType(); result = "abc"; } }; RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null); Buffer buffer = restClientRequest.fileBoundaryInfo("boundary", "name", part); Assert.assertEquals("\r\n" + "--boundary\r\n" + "Content-Disposition: form-data; name=\"name\"; filename=\"null\"\r\n" + "Content-Type: abc\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n", buffer.toString()); }
Example 13
Source File: ApplicantResourceController.java From portals-pluto with Apache License 2.0 | 5 votes |
@CsrfProtected @ServeResourceMethod(portletNames = { "portlet1" }, resourceID = "uploadFiles") @ValidateOnExecution(type = ExecutableType.NONE) public void uploadFiles(ResourceRequest resourceRequest, ResourceResponse resourceResponse) { PortletSession portletSession = resourceRequest.getPortletSession(true); List<Attachment> attachments = attachmentManager.getAttachments(portletSession.getId()); try { Collection<Part> transientMultipartFiles = resourceRequest.getParts(); if (!transientMultipartFiles.isEmpty()) { File attachmentDir = attachmentManager.getAttachmentDir(portletSession.getId()); if (!attachmentDir.exists()) { attachmentDir.mkdir(); } for (Part transientMultipartFile : transientMultipartFiles) { String submittedFileName = transientMultipartFile.getSubmittedFileName(); if (submittedFileName != null) { File copiedFile = new File(attachmentDir, submittedFileName); transientMultipartFile.write(copiedFile.getAbsolutePath()); attachments.add(new Attachment(copiedFile)); } } _writeTabularJSON(resourceResponse.getWriter(), attachments); } } catch (Exception e) { logger.error(e.getMessage(), e); } }
Example 14
Source File: FileAction.java From HongsCORE with MIT License | 5 votes |
@Action("create") public void create(ActionHelper helper) throws HongsException { List list = new ArrayList (); List fils = Synt.asList (helper.getRequestData( ).get("file") ); String uid = Synt.declare(helper.getSessibute(Cnst.UID_SES),"0"); String nid = Core.newIdentity(); String fmt = "%0"+ String.valueOf ( fils.size( ) ).length()+"d" ; int idx = 0; UploadHelper uh = new UploadHelper( ); uh.setUploadPath("static/upload/tmp"); uh.setUploadHref("static/upload/tmp"); for(Object item : fils) { if (item instanceof Part) { Part part = ( Part) item; String name = ( uid +"-"+ nid ) +"-"+ String.format ( fmt , + + idx ) +"."; File file = uh.upload(part , name); String href = uh.getResultHref(/**/); String link = Core.SITE_HREF + Core.BASE_HREF + "/" + href; name = file.getName( ) + "|" + part.getSubmittedFileName(); list.add(Synt.mapOf( "name", name, "href", href, "link", link )); }} helper.reply(Synt.mapOf("list", list)); }
Example 15
Source File: HttpUploadReader.java From tephra with MIT License | 5 votes |
HttpUploadReader(Part part, Map<String, String> map) throws IOException { this.part = part; name = part.getName(); fileName = part.getSubmittedFileName(); contentType = part.getContentType(); size = part.getSize(); inputStream = part.getInputStream(); this.map = map; }
Example 16
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 5 votes |
/** * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME * environment variable, appending a timestamp to end of the uploaded filename. */ // Note: this sample assumes small files are uploaded. For large files or streams use: // Storage.writer(BlobInfo blobInfo, Storage.BlobWriteOption... options) public String uploadFile(Part filePart, final String bucketName) throws IOException { DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = filePart.getSubmittedFileName() + dtString; // The InputStream is closed by default, so we don't need to close it here // Read InputStream into a ByteArrayOutputStream. InputStream is = filePart.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] readBuf = new byte[4096]; while (is.available() > 0) { int bytesRead = is.read(readBuf); os.write(readBuf, 0, bytesRead); } // Convert ByteArrayOutputStream into byte[] BlobInfo blobInfo = storage.create( BlobInfo .newBuilder(bucketName, fileName) // Modify access list to allow all users with link to read file .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))) .build(), os.toByteArray()); // return the public download link return blobInfo.getMediaLink(); }
Example 17
Source File: ApplicantResourceController.java From portals-pluto with Apache License 2.0 | 5 votes |
@CsrfProtected @ServeResourceMethod(portletNames = { "portlet1" }, resourceID = "uploadFiles") @ValidateOnExecution(type = ExecutableType.NONE) public void uploadFiles(ResourceRequest resourceRequest, ResourceResponse resourceResponse) { PortletSession portletSession = resourceRequest.getPortletSession(true); List<Attachment> attachments = attachmentManager.getAttachments(portletSession.getId()); try { Collection<Part> transientMultipartFiles = resourceRequest.getParts(); if (!transientMultipartFiles.isEmpty()) { File attachmentDir = attachmentManager.getAttachmentDir(portletSession.getId()); if (!attachmentDir.exists()) { attachmentDir.mkdir(); } for (Part transientMultipartFile : transientMultipartFiles) { String submittedFileName = transientMultipartFile.getSubmittedFileName(); if (submittedFileName != null) { File copiedFile = new File(attachmentDir, submittedFileName); transientMultipartFile.write(copiedFile.getAbsolutePath()); attachments.add(new Attachment(copiedFile)); } } _writeTabularJSON(resourceResponse.getWriter(), attachments); } } catch (Exception e) { logger.error(e.getMessage(), e); } }
Example 18
Source File: PartBinaryResource.java From eplmp with Eclipse Public License 1.0 | 4 votes |
@POST @ApiOperation(value = "Upload CAD file", response = Response.class) @ApiImplicitParams({ @ApiImplicitParam(name = "upload", paramType = "formData", dataType = "file", required = true) }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Upload success"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 500, message = "Internal server error") }) @Path("/{iteration}/" + PartIteration.NATIVE_CAD_SUBTYPE) @Consumes(MediaType.MULTIPART_FORM_DATA) @RolesAllowed({UserGroupMapping.REGULAR_USER_ROLE_ID}) public Response uploadNativeCADFile( @Context HttpServletRequest request, @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") final String workspaceId, @ApiParam(required = true, value = "Part number") @PathParam("partNumber") final String partNumber, @ApiParam(required = true, value = "Part version") @PathParam("version") final String version, @ApiParam(required = true, value = "Part iteration") @PathParam("iteration") final int iteration) throws EntityNotFoundException, EntityAlreadyExistsException, UserNotActiveException, AccessRightException, NotAllowedException, CreationException, WorkspaceNotEnabledException { try { PartIterationKey partPK = new PartIterationKey(workspaceId, partNumber, version, iteration); Collection<Part> parts = request.getParts(); if (parts.isEmpty() || parts.size() > 1) { return Response.status(Response.Status.BAD_REQUEST).build(); } Part part = parts.iterator().next(); String fileName = part.getSubmittedFileName(); BinaryResource binaryResource = productService.saveNativeCADInPartIteration(partPK, fileName, 0); OutputStream outputStream = storageManager.getBinaryResourceOutputStream(binaryResource); long length = BinaryResourceUpload.uploadBinary(outputStream, part); productService.saveNativeCADInPartIteration(partPK, fileName, length); converterService.convertCADFileToOBJ(partPK, binaryResource); return BinaryResourceUpload.tryToRespondCreated(request.getRequestURI() + URLEncoder.encode(fileName, UTF8_ENCODING)); } catch (IOException | ServletException | StorageException e) { return BinaryResourceUpload.uploadError(e); } }
Example 19
Source File: ChannelController.java From packagedrone with Eclipse Public License 1.0 | 4 votes |
@RequestMapping ( value = "/channel/{channelId}/drop", method = RequestMethod.POST ) public void drop ( @PathVariable ( "channelId" ) final String channelId, @RequestParameter ( required = false, value = "name" ) String name, final @RequestParameter ( "file" ) Part file, final HttpServletResponse response ) throws IOException { response.setContentType ( "text/plain" ); try { if ( name == null || name.isEmpty () ) { name = file.getSubmittedFileName (); } final String finalName = name; this.channelService.accessRun ( By.id ( channelId ), ModifiableChannel.class, channel -> { channel.getContext ().createArtifact ( file.getInputStream (), finalName, null ); } ); } catch ( final Throwable e ) { logger.warn ( "Failed to drop file", e ); final Throwable cause = ExceptionHelper.getRootCause ( e ); if ( cause instanceof VetoArtifactException ) { response.setStatus ( HttpServletResponse.SC_CONFLICT ); response.getWriter ().format ( "Artifact rejected! %s", ( (VetoArtifactException)cause ).getVetoMessage ().orElse ( "No details given" ) ); } else { response.setStatus ( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); response.getWriter ().format ( "Internal error! %s", ExceptionHelper.getMessage ( cause ) ); } return; } response.setStatus ( HttpServletResponse.SC_OK ); response.getWriter ().write ( "OK" ); }
Example 20
Source File: HTMLManagerServlet.java From Tomcat8-Source-Read with MIT License | 4 votes |
protected String upload(HttpServletRequest request, StringManager smClient) { String message = ""; try { while (true) { Part warPart = request.getPart("deployWar"); if (warPart == null) { message = smClient.getString( "htmlManagerServlet.deployUploadNoFile"); break; } String filename = warPart.getSubmittedFileName(); if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) { message = smClient.getString( "htmlManagerServlet.deployUploadNotWar", filename); break; } // Get the filename if uploaded name includes a path if (filename.lastIndexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) File file = new File(host.getAppBaseFile(), filename); if (file.exists()) { message = smClient.getString( "htmlManagerServlet.deployUploadWarExists", filename); break; } ContextName cn = new ContextName(filename, true); String name = cn.getName(); if ((host.findChild(name) != null) && !isDeployed(name)) { message = smClient.getString( "htmlManagerServlet.deployUploadInServerXml", filename); break; } if (isServiced(name)) { message = smClient.getString("managerServlet.inService", name); } else { addServiced(name); try { warPart.write(file.getAbsolutePath()); // Perform new deployment check(name); } finally { removeServiced(name); } } break; } } catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); } return message; }