Java Code Examples for javax.servlet.http.Part#getSize()
The following examples show how to use
javax.servlet.http.Part#getSize() .
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: UploadUtils.java From HotelSystem with Apache License 2.0 | 6 votes |
/** * 用于上传照片 * @param obj 照片的所有者,比如一个user或room * @name uploadPhoto * @notice none * @author <a href="mailto:[email protected]">黄钰朝</a> * @date 2019/4/20 */ public static void uploadPhoto(HttpServletRequest req, Object obj) { String photo = null; try { Part part = req.getPart("photo"); if (part == null) { photo="default.jpg"; } else if (part.getSize() > 0) { photo = upload(part); } } catch (IOException | ServletException | NullPointerException e) { e.printStackTrace(); throw new ServiceException("无法上传照片" + e); } if (obj instanceof User) { User user = (User) obj; user.setPhoto(photo); } if (obj instanceof Room) { Room room = (Room) obj; room.setPhoto(photo); } }
Example 2
Source File: ModifyFoodInfoAction.java From mealOrdering with MIT License | 6 votes |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part image = request.getPart("image"); InputStream imageInputStream = null; if(image.getSize() != 0) imageInputStream = image.getInputStream(); SellerService service = new SellerServiceImpl(); boolean success = service.modifyFoodInfo(request, imageInputStream); if(success){ response.sendRedirect(request.getContextPath() + "/pages/profiles/seller_behind.jsp"); }else{ response.setCharacterEncoding("utf-8"); response.getWriter().print("修改失败!请稍后再试..."); } }
Example 3
Source File: AddNewFoodAction.java From mealOrdering with MIT License | 6 votes |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part image = request.getPart("foodPhoto"); InputStream imageInputStream = null; if (image.getSize() != 0) imageInputStream = image.getInputStream(); SellerService service = new SellerServiceImpl(); boolean success = service.addFood(request, imageInputStream); if (success) { response.sendRedirect(request.getContextPath() + "/pages/profiles/seller_behind.jsp"); } else { response.getWriter().print("添加失败!请稍后再试..."); } }
Example 4
Source File: RestServlet.java From qpid-broker-j with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private <T> T parse(Class<T> type) throws IOException, ServletException { T providedObject; final ObjectMapper mapper = new ObjectMapper(); if (_headers.containsKey("Content-Type") && _request.getHeader("Content-Type") .startsWith("multipart/form-data")) { Map<String, Object> items = new LinkedHashMap<>(); Map<String, String> fileUploads = new HashMap<>(); Collection<Part> parts = _request.getParts(); for (Part part : parts) { if ("data".equals(part.getName()) && "application/json".equals(part.getContentType())) { items = mapper.readValue(part.getInputStream(), LinkedHashMap.class); } else { byte[] data = new byte[(int) part.getSize()]; try (InputStream inputStream = part.getInputStream()) { inputStream.read(data); } fileUploads.put(part.getName(), DataUrlUtils.getDataUrlForBytes(data)); } } items.putAll(fileUploads); providedObject = (T) items; } else { providedObject = mapper.readValue(_request.getInputStream(), type); } return providedObject; }
Example 5
Source File: FileValidator.java From ee7-sandbox with Apache License 2.0 | 5 votes |
@Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { Part part = (Part) value; if(part.getSize()>1024){ throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "file is too large", "file is too large")); } }
Example 6
Source File: UploadServlet.java From selenium with Apache License 2.0 | 5 votes |
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); request.setAttribute(Request.MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG); StringBuilder content = new StringBuilder(); for (Part part : request.getParts()) { if (part.getName().equalsIgnoreCase("upload")) { byte[] buffer = new byte[(int) part.getSize()]; try (InputStream in = part.getInputStream()) { in.read(buffer, 0, (int) part.getSize()); content.append(new String(buffer, StandardCharsets.UTF_8)); } } } // Slow down the upload so we can verify WebDriver waits. try { Thread.sleep(2500); } catch (InterruptedException ignored) { } response.getWriter().write(content.toString()); response.getWriter().write( "<script>window.top.window.onUploadDone();</script>"); response.setStatus(HttpServletResponse.SC_OK); }
Example 7
Source File: PostStudentProfilePictureAction.java From teammates with GNU General Public License v2.0 | 5 votes |
@Override public ActionResult execute() { try { Part image = req.getPart("studentprofilephoto"); if (image == null) { throw new InvalidHttpRequestBodyException(Const.StatusMessages.STUDENT_PROFILE_NO_PICTURE_GIVEN); } if (image.getSize() > Const.SystemParams.MAX_PROFILE_PIC_SIZE) { throw new InvalidHttpRequestBodyException(Const.StatusMessages.STUDENT_PROFILE_PIC_TOO_LARGE); } if (!image.getContentType().startsWith("image/")) { throw new InvalidHttpRequestBodyException(Const.StatusMessages.STUDENT_PROFILE_NOT_A_PICTURE); } byte[] imageData = new byte[(int) image.getSize()]; try (InputStream is = image.getInputStream()) { is.read(imageData); } String pictureKey = GoogleCloudStorageHelper.writeImageDataToGcs(userInfo.id, imageData, image.getContentType()); logic.updateOrCreateStudentProfile( StudentProfileAttributes.updateOptionsBuilder(userInfo.id) .withPictureKey(pictureKey) .build()); StudentProfilePictureResults dataFormat = new StudentProfilePictureResults(pictureKey); return new JsonResult(dataFormat); } catch (InvalidParametersException ipe) { throw new InvalidHttpRequestBodyException(ipe.getMessage(), ipe); } catch (ServletException | IOException e) { return new JsonResult(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
Example 8
Source File: PartHandler.java From development with Apache License 2.0 | 5 votes |
public static boolean isEmpty(Part file) { if(file==null){ return true; } return !(file.getSize()>0); }
Example 9
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 10
Source File: UploadHelperImpl.java From tephra with MIT License | 5 votes |
@Override public void upload(HttpServletRequest request, HttpServletResponse response, String uploader) { cors.set(request, response); if (cors.is(request, response)) return; try { OutputStream outputStream = serviceHelper.setContext(request, response, uploader); List<UploadReader> readers = new ArrayList<>(); Map<String, String> map = new HashMap<>(); request.getParameterMap().forEach((name, value) -> map.put(name, converter.toString(value))); for (Part part : request.getParts()) if (!map.containsKey(part.getName()) && !validator.isEmpty(part.getSubmittedFileName()) && part.getSize() <= maxFileSize) readers.add(new HttpUploadReader(part, map)); if (readers.isEmpty()) return; response.setCharacterEncoding(context.getCharset(null)); outputStream.write(uploaders.get(uploader).upload(readers)); outputStream.flush(); outputStream.close(); } catch (Throwable e) { logger.warn(e, "处理文件上传时发生异常!"); } finally { closables.close(); } }
Example 11
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 12
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 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: ImageUpload.java From OnlineShoppingSystem with MIT License | 4 votes |
/** * 上传多个图片 * * @param request * @return */ public boolean uploadImages(HttpServletRequest request) { boolean success = false; int count = -1; ArrayList<Part> images; try { images = (ArrayList<Part>) request.getParts(); count = images.size(); for (Part image : images) { System.out.println(image.getName()); InputStream imageInputStream = null; if (image != null && image.getSize() != 0) { try { imageInputStream = image.getInputStream(); if (imageInputStream != null) { String imagedir = request.getServletContext() .getInitParameter("imagedir") + File.separator + "avatars" + 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; System.out.println(targetFile); try { FileUtils.copyInputStreamToFile(imageInputStream, new File(targetFile)); count--; } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e1) { e1.printStackTrace(); } finally { imageInputStream.close(); } } } } catch (IOException | ServletException e3) { e3.printStackTrace(); } if (count == 0) { success = true; } else { success = false; } return success; }
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: UpdateAvatarAction.java From OnlineShoppingSystem with MIT License | 3 votes |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); /* 1. read parameter */ String uid = (String) request.getSession().getAttribute("usreId"); Part image = request.getPart("image"); /* 2. invoke service */ InputStream imageIS = null; if (image != null && image.getSize() != 0) imageIS = image.getInputStream(); String newAvatarAddr = UserService.updateAvatar(uid, request.getServletContext(), imageIS); /* 3. set session */ request.getSession().setAttribute("userAvatarAddr", newAvatarAddr); /* 4. return JSON */ Gson gson = new Gson(); JsonObject result = new JsonObject(); result.addProperty("avatar", newAvatarAddr); }