Java Code Examples for javax.servlet.http.Part#getContentType()
The following examples show how to use
javax.servlet.http.Part#getContentType() .
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: MenuManagerController.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
/** Upload a new molgenis logo */ @PreAuthorize("hasAnyRole('ROLE_SU')") @PostMapping("/upload-logo") public String uploadLogo(@RequestParam("logo") Part part, Model model) throws IOException { String contentType = part.getContentType(); if ((contentType == null) || !contentType.startsWith("image")) { model.addAttribute("errorMessage", ERRORMESSAGE_LOGO); } else { // Create the logo subdir in the filestore if it doesn't exist File logoDir = new File(fileStore.getStorageDir() + "/logo"); if (!logoDir.exists() && !logoDir.mkdir()) { throw new IOException("Unable to create directory [" + logoDir.getAbsolutePath() + "]"); } // Store the logo in the logo dir of the filestore String file = "/logo/" + FileUploadUtils.getOriginalFileName(part); try (InputStream inputStream = part.getInputStream()) { fileStore.store(inputStream, file); } // Set logo appSettings.setLogoNavBarHref(file); } return init(model); }
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: 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 4
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 5
Source File: MockMultiPartServlet.java From requests with BSD 2-Clause "Simplified" License | 6 votes |
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG); Collection<Part> parts = request.getParts(); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.setStatus(HttpServletResponse.SC_OK); OutputStream out = response.getOutputStream(); for (Part part : parts) { out.write(part.getName().getBytes(StandardCharsets.UTF_8)); out.write('\n'); if (part.getContentType() != null) { out.write(part.getContentType().getBytes(StandardCharsets.UTF_8)); out.write('\n'); } try (InputStream in = part.getInputStream()) { InputStreams.transferTo(in, out); } out.write('\n'); } }
Example 6
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 7
Source File: SolrRequestParsers.java From lucene-solr with Apache License 2.0 | 5 votes |
public PartContentStream(Part part ) { this.part = part; contentType = part.getContentType(); name = part.getName(); sourceInfo = part.getSubmittedFileName(); size = part.getSize(); }
Example 8
Source File: StandardMultipartHttpServletRequest.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public String getMultipartContentType(String paramOrFileName) { try { Part part = getPart(paramOrFileName); return (part != null ? part.getContentType() : null); } catch (Exception ex) { throw new MultipartException("Could not access multipart servlet request", ex); } }
Example 9
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 10
Source File: StandardMultipartHttpServletRequest.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public String getMultipartContentType(String paramOrFileName) { try { Part part = getPart(paramOrFileName); return (part != null ? part.getContentType() : null); } catch (Throwable ex) { throw new MultipartException("Could not access multipart servlet request", ex); } }
Example 11
Source File: StandardMultipartHttpServletRequest.java From java-technology-stack with MIT License | 5 votes |
@Override public String getMultipartContentType(String paramOrFileName) { try { Part part = getPart(paramOrFileName); return (part != null ? part.getContentType() : null); } catch (Throwable ex) { throw new MultipartException("Could not access multipart servlet request", ex); } }
Example 12
Source File: StandardMultipartHttpServletRequest.java From spring-analysis-note with MIT License | 4 votes |
@Override public String getMultipartContentType(String paramOrFileName) { try { Part part = getPart(paramOrFileName); return (part != null ? part.getContentType() : null); } catch (Throwable ex) { throw new MultipartException("Could not access multipart servlet request", ex); } }
Example 13
Source File: SellerServiceImpl.java From OnlineShoppingSystem with MIT License | 4 votes |
public boolean addGoodsImage(HttpServletRequest request, int goodsId) { boolean flag = false; int count = -1; ArrayList<Part> images; try { images = (ArrayList<Part>) request.getParts(); count = images.size(); for (Part image : images) { if (image.getContentType() == null) { continue; } // System.out.println(image.getContentType()); InputStream imageInputStream = null; if (image != null && image.getSize() != 0) { try { imageInputStream = image.getInputStream(); if (imageInputStream != null) { String imagedir = request.getServletContext() .getInitParameter("imagedir") + File.separator; // 图片名格式:20161123204206613375.jpg。 // 代表 2016-11-23 20:42:06.613 + 3 位 0 - 9 间随机数字 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); StringBuilder imageName = new StringBuilder( dateFormat.format(new Date())); Random random = new Random(); for (int i = 0; i < 3; ++i) { imageName.append(random.nextInt(10)); } imageName.append(".jpg"); String targetFile = imagedir + imageName; try { FileUtils.copyInputStreamToFile(imageInputStream, new File(targetFile)); count--; dao.addGoodsImage("/images/goods/" + imageName, goodsId); // 更新数据库 // System.out.println(imagedir); // System.out.println(imageName); // System.out.println(count); } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e1) { e1.printStackTrace(); } finally { imageInputStream.close(); } } } } catch (IOException | ServletException e3) { e3.printStackTrace(); } if (count == 0) { flag = true; } else { flag = false; } return flag; }
Example 14
Source File: FileUploadServlet.java From Tutorials with Apache License 2.0 | 4 votes |
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); // gets absolute path of the web application String applicationPath = request.getServletContext().getRealPath(""); // constructs path of the directory to save uploaded file String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR; // creates upload folder if it does not exists File uploadFolder = new File(uploadFilePath); if (!uploadFolder.exists()) { uploadFolder.mkdirs(); } PrintWriter writer = response.getWriter(); // write all files in upload folder for (Part part : request.getParts()) { if (part != null && part.getSize() > 0) { String fileName = part.getSubmittedFileName(); String contentType = part.getContentType(); // allows only JPEG files to be uploaded if (!contentType.equalsIgnoreCase("image/jpeg")) { continue; } part.write(uploadFilePath + File.separator + fileName); writer.append("File successfully uploaded to " + uploadFolder.getAbsolutePath() + File.separator + fileName + "<br>\r\n"); } } }
Example 15
Source File: ImportServlet.java From BLELocalization with MIT License | 4 votes |
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InputStream is = null; OutputStream os = null; try { Part part = null; try { part = request.getPart("file"); } catch (Exception e) { } String contentType = null; int contentLength = -1; if (part == null) { is = request.getInputStream(); contentType = request.getContentType(); contentLength = request.getContentLength(); } else { is = part.getInputStream(); contentType = part.getContentType(); contentLength = (int) part.getSize(); } response.addHeader("Access-Control-Allow-Origin", "*"); if (contentType != null) { response.setContentType(contentType); } if (contentLength > 0) { response.setContentLength(contentLength); } os = response.getOutputStream(); byte data[] = new byte[4096]; int len = 0; while ((len = is.read(data, 0, data.length)) > 0) { os.write(data, 0, len); } os.flush(); } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } }
Example 16
Source File: MemoryUploadServlet.java From BotLibre with Eclipse Public License 1.0 | 4 votes |
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PageStats.page(request); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); LoginBean loginBean = (LoginBean)request.getSession().getAttribute("loginBean"); if (loginBean == null) { response.sendRedirect("index.jsp"); return; } BotBean botBean = loginBean.getBotBean(); MemoryBean bean = loginBean.getBean(MemoryBean.class); try { String postToken = (String)request.getParameter("postToken"); loginBean.verifyPostToken(postToken); String instance = (String)request.getParameter("instance"); if (instance != null) { if (botBean.getInstance() == null || !String.valueOf(botBean.getInstanceId()).equals(instance)) { botBean.validateInstance(instance); } } if (!botBean.isConnected()) { request.getRequestDispatcher("memory.jsp").forward(request, response); return; } botBean.checkAdmin(); String importFormat = (String)request.getParameter("import-format"); String encoding = (String)request.getParameter("import-encoding"); String pin = (String)request.getParameter("pin"); Part filePart = request.getPart("file"); if ((filePart != null) && (filePart.getSize() > 0)) { if (filePart.getContentType() != null && filePart.getContentType().equals("csv")) { importFormat = "csv"; } String fileName = getFileName(filePart); InputStream stream = filePart.getInputStream(); bean.importFile(fileName, stream, importFormat, encoding, "on".equals(pin)); } else { throw new BotException("Missing file"); } request.getRequestDispatcher("memory.jsp").forward(request, response); } catch (Exception failed) { botBean.error(failed); request.getRequestDispatcher("memory.jsp").forward(request, response); } }
Example 17
Source File: MultipartPortlet.java From portals-pluto with Apache License 2.0 | 4 votes |
@ActionMethod(portletName = "MultipartPortlet") public void handleDialog(ActionRequest req, ActionResponse resp) throws IOException, PortletException { List<String> lines = new ArrayList<String>(); req.getPortletSession().setAttribute("lines", lines); lines.add("handling dialog"); StringBuilder txt = new StringBuilder(128); String clr = req.getActionParameters().getValue("color"); txt.append("Color: ").append(clr); lines.add(txt.toString()); logger.debug(txt.toString()); resp.getRenderParameters().setValue("color", clr); txt.setLength(0); Part part = null; try { part = req.getPart("file"); } catch (Throwable t) {} if ((part != null) && (part.getSubmittedFileName() != null) && (part.getSubmittedFileName().length() > 0)) { txt.append("Uploaded file name: ").append(part.getSubmittedFileName()); txt.append(", part name: ").append(part.getName()); txt.append(", size: ").append(part.getSize()); txt.append(", content type: ").append(part.getContentType()); lines.add(txt.toString()); logger.debug(txt.toString()); txt.setLength(0); txt.append("Headers: "); String sep = ""; for (String hdrname : part.getHeaderNames()) { txt.append(sep).append(hdrname).append("=").append(part.getHeaders(hdrname)); sep = ", "; } lines.add(txt.toString()); logger.debug(txt.toString()); // Store the file in a temporary location in the webapp where it can be served. try { String fn = part.getSubmittedFileName(); String ct = part.getContentType(); if (ct != null && (ct.equals("text/plain") || ct.matches("image/(?:png|gif|jpg|jpeg)"))) { String ext = ct.replaceAll("\\w+/", ""); lines.add("determined extension " + ext + " from content type " + ct); File img = getFile(); if (img.exists()) { lines.add("deleting existing temp file: " + img.getCanonicalPath()); img.delete(); } InputStream is = part.getInputStream(); Files.copy(is, img.toPath(), StandardCopyOption.REPLACE_EXISTING); } else { lines.add("Bad file type. Must be plain text or image (gif, jpeg, png)."); } resp.getRenderParameters().setValue("fn", fn); resp.getRenderParameters().setValue("ct", ct); } catch (Exception e) { lines.add("Exception doing I/O: " + e.toString()); txt.setLength(0); txt.append("Problem getting temp file: " + e.getMessage() + "\n"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.flush(); txt.append(sw.toString()); logger.warn(txt.toString()); } } else { lines.add("file part was null"); } }