List of usage examples for org.springframework.web.multipart MultipartFile getSize
long getSize();
From source file:com.sunflower.petal.controller.ImageController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) { log.debug("uploadPost called"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf; List<Image> list = new LinkedList<Image>(); while (itr.hasNext()) { mpf = request.getFile(itr.next()); log.debug("Uploading {}", mpf.getOriginalFilename()); String newFilenameBase = UUID.randomUUID().toString(); String originalFileExtension = mpf.getOriginalFilename() .substring(mpf.getOriginalFilename().lastIndexOf(".")); String newFilename = newFilenameBase + originalFileExtension; String storageDirectory = fileUploadDirectory; String contentType = mpf.getContentType(); File newFile = new File(storageDirectory + "/" + newFilename); try {//from ww w . j a v a 2s . c o m mpf.transferTo(newFile); BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); String thumbnailFilename = newFilenameBase + "-thumbnail.png"; File thumbnailFile = new File(storageDirectory + "/" + thumbnailFilename); ImageIO.write(thumbnail, "png", thumbnailFile); Image image = new Image(); image.setName(mpf.getOriginalFilename()); image.setThumbnailFilename(thumbnailFilename); image.setNewFilename(newFilename); image.setContentType(contentType); image.setSize(mpf.getSize()); image = imageService.create(image); image.setUrl("/picture/" + image.getId()); image.setThumbnailUrl("/thumbnail/" + image.getId()); image.setDeleteUrl("/delete/" + image.getId()); image.setDeleteType("DELETE"); list.add(image); } catch (IOException e) { log.error("Could not upload file " + mpf.getOriginalFilename(), e); } } Map<String, Object> files = new HashMap<String, Object>(); files.put("files", list); return files; }
From source file:net.duckling.ddl.web.api.rest.FileEditController.java
@RequestMapping(value = "/fileShared", method = RequestMethod.POST) public void fileShared(@RequestParam(value = "path", required = false) String path, @RequestParam("file") MultipartFile file, @RequestParam(value = "ifExisted", required = false) String ifExisted, HttpServletRequest request, HttpServletResponse response) throws IOException { String uid = getCurrentUid(request); int tid = getCurrentTid(); path = StringUtils.defaultIfBlank(path, PathName.DELIMITER); LOG.info("file shared start... {uid:" + uid + ",tid:" + tid + ",path:" + path + ",fileName:" + file.getOriginalFilename() + ",ifExisted:" + ifExisted + "}"); Resource parent = folderPathService.getResourceByPath(tid, path); if (parent == null) { LOG.error("path not found. {tid:" + tid + ", path:" + path + "}"); writeError(ErrorMsg.NOT_FOUND, response); return;/* w w w . ja va 2 s.co m*/ } List<Resource> list = resourceService.getResourceByTitle(tid, parent.getRid(), LynxConstants.TYPE_FILE, file.getOriginalFilename()); if (list.size() > 0 && !IF_EXISTED_UPDATE.equals(ifExisted)) { LOG.error("file existed. {ifExisted:" + ifExisted + ",fileName:" + file.getOriginalFilename() + "}"); writeError(ErrorMsg.EXISTED, response); return; } FileVersion fv = null; try { fv = resourceOperateService.upload(uid, getCurrentTid(), parent.getRid(), file.getOriginalFilename(), file.getSize(), file.getInputStream()); } catch (NoEnoughSpaceException e) { LOG.error("no enough space. {tid:" + tid + ",size:" + file.getSize() + ",fileName:" + file.getOriginalFilename() + "}"); writeError(ErrorMsg.NO_ENOUGH_SPACE, response); return; } ShareResource sr = shareResourceService.get(fv.getRid()); if (sr == null) { sr = createShareResource(fv.getRid(), uid); } else { sr.setLastEditor(uid); sr.setLastEditTime(new Date()); shareResourceService.update(sr); } sr.setTitle(fv.getTitle()); sr.setShareUrl(sr.generateShareUrl(urlGenerator)); LOG.info("file uploaded and shared successfully. {tid:" + tid + ",path:" + path + ",title:" + fv.getTitle() + "}"); JsonUtil.write(response, VoUtil.getShareResourceVo(sr)); }
From source file:com.topsec.tsm.sim.sysconfig.web.SystemConfigController.java
@RequestMapping(value = "licenseImport", produces = "text/html;charset=utf-8") @ResponseBody/* ww w . j av a 2s.co m*/ public Object licenseImport(SID sid, @RequestParam("theLicenseFile") MultipartFile theLicenseFile, HttpServletRequest request) throws Exception { Result result = new Result(); if (theLicenseFile == null) { return JSON.toJSONString(result.buildError("?")); } //? if (theLicenseFile.getSize() > maxPostSize) { return JSON.toJSONString(result.buildError("??")); } //? File basefile = new File(TMP_LICENSE_PATH + theLicenseFile.getOriginalFilename()); if (!basefile.exists()) { FileUtils.forceMkdir(basefile); } try { // theLicenseFile.transferTo(basefile); Result checkResult = LicenceServiceUtil.checkLicenseFile(basefile, "TAEX-S", "TAEX_S"); AuditLogFacade.userOperation("??", sid.getUserName(), checkResult.getMessage(), IpAddress.IPV4_LOCALHOST, Severity.HIGHEST, AuditCategoryDefinition.SYS_UPGRADE, result.isSuccess()); log.warn(checkResult.getMessage()); result.build(checkResult.isSuccess(), checkResult.getMessage()); } catch (Exception e) { result.build(false, "??"); } finally { basefile.delete(); } return JSON.toJSONString(result); }
From source file:com.devnexus.ting.web.controller.admin.OrganizerController.java
@RequestMapping(value = "/s/admin/organizer/{organizerId}", method = RequestMethod.POST) public String editOrganizer(@PathVariable("organizerId") Long organizerId, @RequestParam MultipartFile pictureFile, @Valid Organizer organizerForm, BindingResult result, RedirectAttributes redirectAttributes, HttpServletRequest request) { if (request.getParameter("cancel") != null) { return "redirect:/s/admin/index"; }// w w w .ja va 2s . c o m if (result.hasErrors()) { return "/admin/add-organizer"; } final Organizer organizerFromDb = businessService.getOrganizerWithPicture(organizerId); if (request.getParameter("delete") != null) { businessService.deleteOrganizer(organizerFromDb); //FlashMap.setSuccessMessage("The organizer was deleted successfully."); return "redirect:/s/admin/organizers"; } organizerFromDb.setBio(organizerForm.getBio()); organizerFromDb.setFirstName(organizerForm.getFirstName()); organizerFromDb.setLastName(organizerForm.getLastName()); organizerFromDb.setCompany(organizerForm.getCompany()); organizerFromDb.setGooglePlusId(organizerForm.getGooglePlusId()); organizerFromDb.setLinkedInId(organizerForm.getLinkedInId()); organizerFromDb.setTwitterId(organizerForm.getTwitterId()); organizerFromDb.setLanyrdId(organizerForm.getLanyrdId()); organizerFromDb.setGithubId(organizerForm.getGithubId()); organizerFromDb.setSortOrder(organizerForm.getSortOrder()); if (pictureFile != null && pictureFile.getSize() > 0) { final FileData pictureData; if (organizerFromDb.getPicture() == null) { pictureData = new FileData(); } else { pictureData = organizerFromDb.getPicture(); } try { pictureData.getId(); pictureData.setFileData(IOUtils.toByteArray(pictureFile.getInputStream())); pictureData.setFileSize(pictureFile.getSize()); pictureData.setFileModified(new Date()); pictureData.setName(pictureFile.getOriginalFilename()); } catch (IOException e) { throw new IllegalStateException( "Error while processing image for speaker " + organizerForm.getFirstLastName(), e); } organizerForm.setPicture(pictureData); String message = "File '" + organizerForm.getPicture().getName() + "' uploaded successfully"; redirectAttributes.addFlashAttribute("successMessage", message); } businessService.saveOrganizer(organizerFromDb); redirectAttributes.addFlashAttribute("successMessage", "The organizer was edited successfully."); return "redirect:/s/admin/organizers"; }
From source file:com.sfy.controller.SiteManageController.java
@RequestMapping(value = "/uploadForPage") @ResponseBody// w w w .j av a 2 s. c om public Result<Map<String, String>> uploadForPage(MultipartHttpServletRequest request) { Result<Map<String, String>> resultMap = new Result<Map<String, String>>(false); resultMap.setResult(new HashMap<String, String>()); Iterator<String> iterator = request.getFileNames(); Iterator<String> iteratorOperator = request.getFileNames(); MultipartFile multipartFile; Map<String, String> duplicateName = new HashMap<String, String>(); List<String> fileTypeAllow = new ArrayList<String>(); fileTypeAllow.add("gif"); fileTypeAllow.add("jpg"); fileTypeAllow.add("jpeg"); fileTypeAllow.add("png"); fileTypeAllow.add("doc"); fileTypeAllow.add("xsl"); fileTypeAllow.add("ppt"); fileTypeAllow.add("rar"); fileTypeAllow.add("zip"); fileTypeAllow.add("pdf"); boolean isDuplicate = false; try { while (iterator.hasNext()) { multipartFile = request.getFile(iterator.next()); String fileName = multipartFile.getOriginalFilename(); long fileSize = multipartFile.getSize(); String[] arr = fileName.split("\\."); int tmp = arr.length; String fileType = arr[tmp - 1]; if (fileSize > 5000000 || !fileTypeAllow.contains(fileType)) { resultMap.setSuccess(false); resultMap.setLocalizedMessage("???"); resultMap.setErrorStack("???"); resultMap.setErrorCode("501"); return resultMap; } if (resultMap.getResult().containsKey(fileName)) { isDuplicate = true; duplicateName.put(fileName, ""); } } while (!isDuplicate && iteratorOperator.hasNext()) { multipartFile = request.getFile(iteratorOperator.next()); String fileName = multipartFile.getOriginalFilename(); String contentType = multipartFile.getContentType(); String uuid = UUID.randomUUID().toString() + "_" + fileName; // String url = jss.upload(uuid, contentType, multipartFile.getBytes()); // resultMap.getResult().put(fileName, url); } } catch (Exception e) { resultMap.setErrorCode("500"); resultMap.setErrorStack(e.toString()); resultMap.setLocalizedMessage(e.getLocalizedMessage()); return resultMap; } if (duplicateName.size() > 0) { resultMap.setSuccess(false); resultMap.setResult(duplicateName); } else { resultMap.setSuccess(true); } return resultMap; }
From source file:com.codestudio.dorm.web.support.spring.upload.FileUploadSupport.java
/** * /*from ww w . ja va 2 s . c om*/ * * @param file * @param type * @return */ public Attachment upload(long userId, MultipartFile file, String type) { if (StringUtils.isBlank(type)) { type = DEFAULT_TYPE; } FileOutputStream fs = null; InputStream is = null; if (file == null) { return null; } try { is = file.getInputStream(); String orgFileName = file.getOriginalFilename(); int i = orgFileName.lastIndexOf('.'); String ext = ""; if (i > 0) { ext = orgFileName.substring(i); } Date now = new Date(); String filePath = "/" + type + "/" + DateUtils.dateConvert2String(now, DateUtils.DATEPATTERN_YYYY_MM_DD4FILE) + "/"; String fileName = now.getTime() + "" + ((int) (Math.random() * 10)); File f = new File(uploadFilePath + filePath); if (!f.exists()) { f.mkdirs(); } fs = new FileOutputStream(uploadFilePath + filePath + fileName + ext); byte[] buffer = new byte[1024 * 1024]; int byteread = 0; while ((byteread = is.read(buffer)) != -1) { fs.write(buffer, 0, byteread); fs.flush(); } // ??? Attachment attachment = new Attachment(); attachment.setSrcName(file.getOriginalFilename()); attachment.setDescName(fileName); attachment.setFileType(type); attachment.setExt(ext); attachment.setPath(filePath); attachment.setSize(file.getSize()); attachment.setUserId(userId); attachmentService.add(attachment); return attachment; } catch (Exception e) { logger.error("upload file error:", e); } finally { try { fs.close(); is.close(); } catch (Exception e) { logger.error("close file error:", e); } } return null; }
From source file:com.siblinks.ws.service.impl.PostServiceImpl.java
/** * This method is validate image file type, size, length * * @param files/*from ww w . j a v a 2s . c o m*/ * These are file upload image * @return Message error */ private String validateFileImage(final MultipartFile[] files) { String error = ""; String name = ""; String sample = environment.getProperty("file.upload.image.type"); String limitSize = environment.getProperty("file.upload.image.size"); String maxLength = environment.getProperty("file.upload.image.length"); long totalSize = 0; if (files != null && files.length > 0) { if (files.length > Integer.parseInt(maxLength)) { return "You only upload " + maxLength + " image"; } for (MultipartFile file : files) { name = file.getOriginalFilename(); if (!StringUtil.isNull(name)) { String nameExt = FilenameUtils.getExtension(name.toLowerCase()); boolean status = sample.contains(nameExt); if (!status) { return "Error Format"; } } totalSize += file.getSize(); } if (totalSize > Long.parseLong(limitSize)) { } } return error; }
From source file:com.topsec.tsm.sim.asset.web.AssetListController.java
@RequestMapping("uploadExcelFile") public void uploadExcelFile(HttpServletRequest request, HttpServletResponse response, SID sid) throws Exception { // MultipartHttpRequest (multipartResolver) setEncode(request, response);// w w w .j ava 2 s. co m MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // MultipartFile file = multipartRequest.getFile("fileToUpload"); PrintWriter printWriter; if (file.getSize() > 10L * 1024 * 1024 || !(file.getOriginalFilename().endsWith(".xls"))) { JSONObject result = new JSONObject(); result.put("uploadInfo", "failed"); result.put("errorInfo", "10mb! "); printWriter = response.getWriter(); printWriter.print(result); printWriter.flush(); return; } int total = 0; int successno = 0; try { SID.setCurrentUser(sid); DeviceService deviceService = (DeviceService) SpringWebUtil.getBean("assetService", request); List<Device> deviceList = xlsToMap(file, sid); total = deviceList.size(); List<Result> resultList = batchSaveDevice(deviceList, deviceService); successno = getSuccess(resultList); } catch (Exception e1) { e1.printStackTrace(); } finally { SID.removeCurrentUser(); } try { ImportResult importResult = new ImportResult(); importResult.setSuccessCount(successno); importResult.setTotalCount(total); importResult.setMessage("success"); importResult.initErrorContent(formatErrorMap, dataConflictErrorMap); importResult.setStatus(true); importResult.setMarks(marks); Object json = JSON.toJSON(importResult); printWriter = response.getWriter(); printWriter.print(json); printWriter.flush(); } catch (IOException e) { } }
From source file:com.topsec.tsm.sim.sysconfig.web.SystemConfigController.java
@RequestMapping(value = "modifyCompanyInfo") @ResponseBody/*from w w w . j a v a 2 s.c om*/ public Object modifyCompanyInfo(@RequestParam(value = "companyLogoFile") MultipartFile companyLogoFile, HttpServletRequest request) throws Exception { Result result = new Result(); String companyName = StringUtil.recode(request.getParameter("companyName")); String productName = StringUtil.recode(request.getParameter("productName")); String companyLogo = companyLogoFile.getOriginalFilename(); String path = request.getSession().getServletContext().getRealPath("/"); String logoPath = ""; if (StringUtil.isNotBlank(companyLogo)) { if (companyLogoFile.getSize() > 1024 * 1024) { return result.buildError("?1M?logo"); } logoPath = "/img/skin/top/user_logo." + FilenameUtils.getExtension(companyLogo); String filePath = path + logoPath; companyLogoFile.transferTo(new File(filePath)); BufferedImage src = javax.imageio.ImageIO.read(new File(filePath)); int width = src.getWidth(); int height = src.getHeight(); if (width > 500 || width < 300 || height > 51 || height < 40) { return result.buildError( "300px~500px?40px~51px?logo(425px*51px)"); } } companyLogo = StringUtil.isBlank(companyLogo) ? CommonUtils.getCompanyLogo() : logoPath; companyName = StringUtil.ifBlank(companyName, CommonUtils.getCompanyName()); productName = StringUtil.ifBlank(productName, CommonUtils.getProductName()); CommonUtils.setCompanyInfo(companyLogo, companyName, productName); return result.build(true, "?"); }