List of usage examples for org.springframework.web.multipart MultipartFile getSize
long getSize();
From source file:org.sparkcommerce.cms.file.service.StaticAssetServiceImpl.java
@Override @Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER) public StaticAsset createStaticAssetFromFile(MultipartFile file, Map<String, String> properties) { if (properties == null) { properties = new HashMap<String, String>(); }/* w w w . j a v a2 s . com*/ String fullUrl = buildAssetURL(properties, file.getOriginalFilename()); StaticAsset newAsset = staticAssetDao.readStaticAssetByFullUrl(fullUrl); int count = 0; while (newAsset != null) { count++; //try the new format first, then the old newAsset = staticAssetDao.readStaticAssetByFullUrl(getCountUrl(fullUrl, count, false)); if (newAsset == null) { newAsset = staticAssetDao.readStaticAssetByFullUrl(getCountUrl(fullUrl, count, true)); } } if (count > 0) { fullUrl = getCountUrl(fullUrl, count, false); } try { ImageMetadata metadata = imageArtifactProcessor.getImageMetadata(file.getInputStream()); newAsset = new ImageStaticAssetImpl(); ((ImageStaticAsset) newAsset).setWidth(metadata.getWidth()); ((ImageStaticAsset) newAsset).setHeight(metadata.getHeight()); } catch (Exception e) { //must not be an image stream newAsset = new StaticAssetImpl(); } if (storeAssetsOnFileSystem) { newAsset.setStorageType(StorageType.FILESYSTEM); } else { newAsset.setStorageType(StorageType.DATABASE); } newAsset.setName(file.getOriginalFilename()); getMimeType(file, newAsset); newAsset.setFileExtension(getFileExtension(file.getOriginalFilename())); newAsset.setFileSize(file.getSize()); newAsset.setFullUrl(fullUrl); return staticAssetDao.addOrUpdateStaticAsset(newAsset, false); }
From source file:org.springframework.cloud.netflix.zuul.FormZuulServletProxyApplicationTests.java
@RequestMapping(value = "/file", method = RequestMethod.POST) public String file(@RequestParam(required = false) MultipartFile file) throws IOException { byte[] bytes = new byte[0]; if (file != null) { if (file.getSize() > 1024) { bytes = new byte[1024]; InputStream inputStream = file.getInputStream(); inputStream.read(bytes);//ww w. j a v a 2 s . com byte[] buffer = new byte[1024 * 1024 * 10]; while (inputStream.read(buffer) >= 0) { log.info("Read more bytes"); } } else { bytes = file.getBytes(); } } return "Posted! " + new String(bytes); }
From source file:org.springframework.integration.http.FileCopyingMultipartFileReader.java
public MultipartFile readMultipartFile(MultipartFile multipartFile) throws IOException { File upload = File.createTempFile(this.prefix, this.suffix, this.directory); multipartFile.transferTo(upload);//from w ww . j av a 2 s . c om UploadedMultipartFile uploadedMultipartFile = new UploadedMultipartFile(upload, multipartFile.getSize(), multipartFile.getContentType(), multipartFile.getName(), multipartFile.getOriginalFilename()); if (logger.isDebugEnabled()) { logger.debug("copied uploaded file [" + multipartFile.getOriginalFilename() + "] to [" + upload.getAbsolutePath() + "]"); } return uploadedMultipartFile; }
From source file:org.tightblog.service.FileService.java
/** * Determine if file can be saved given current blogger settings. * * @param fileToTest MediaFile attempting to save * @param messages output parameter for resource bundle messages, or null if not necessary to receive them * @return true if the file can be saved, false otherwise. */// w ww. jav a2 s. co m public boolean canSave(MultipartFile fileToTest, String weblogHandle, Map<String, List<String>> messages) { WebloggerProperties webloggerProperties = webloggerPropertiesRepository.findOrNull(); // first check, is uploading enabled? if (!allowUploads) { if (messages != null) { messages.put("error.upload.disabled", null); } return false; } // second check, is upload type allowed? if (!checkFileType(fileToTest.getOriginalFilename(), fileToTest.getContentType())) { if (messages != null) { messages.put("error.upload.forbiddenFile", Collections.singletonList(fileToTest.getContentType())); } return false; } // third check, does upload exceed max size for file? log.debug("File size = {}, Max allowed = {}MB", fileToTest.getSize(), maxFileSizeMb); if (fileToTest.getSize() > maxFileSizeMb * Utilities.ONE_MB_IN_BYTES) { if (messages != null) { messages.put("error.upload.filemax", Collections.singletonList(Long.toString(maxFileSizeMb))); } return false; } // fourth check, does file cause weblog to exceed quota? long maxAllocationMB = webloggerProperties.getMaxFileUploadsSizeMb(); long maxAllocationBytes = maxAllocationMB * Utilities.ONE_MB_IN_BYTES; try { File storageDirectory = this.getRealFile(weblogHandle, null); long alreadyUsedSpace = getDirSize(storageDirectory); log.debug("File size = {}, current allocation space taken = {}, max allowed = {}MB", fileToTest.getSize(), alreadyUsedSpace, maxAllocationMB); if (alreadyUsedSpace + fileToTest.getSize() > maxAllocationBytes) { if (messages != null) { messages.put("error.upload.blogmax", Collections.singletonList(Long.toString(maxAllocationMB))); } return false; } } catch (Exception ex) { // shouldn't ever happen, means the weblogs uploads dir is bad // somehow // rethrow as a runtime exception throw new RuntimeException(ex); } return true; }
From source file:org.uhp.portlets.news.web.validator.ItemValidator.java
public void validateFileSize(final long maxSize, final ItemForm itemForm, final Errors errors) { MultipartFile file = itemForm.getExternal().getFile(); if (file != null) { long size = file.getSize(); if (size >= maxSize) { errors.rejectValue("external.file", "ITEM_FILE_WRONG_SIZE", "The file chosen is too big."); } else if (size == 0) { errors.rejectValue("external.file", "ITEM_FILE_IS_EMPTY", "You must select a file"); }/*from w w w . j a v a2 s. com*/ } else { errors.rejectValue("external.file", "ITEM_FILE_IS_EMPTY", "You must select a file"); } }
From source file:ru.mystamps.web.support.beanvalidation.MaxFileSizeValidator.java
@Override public boolean isValid(MultipartFile file, ConstraintValidatorContext context) { if (file == null) { return true; }//from w w w. j a v a 2 s .c o m if (StringUtils.isEmpty(file.getOriginalFilename())) { return true; } return file.getSize() <= maxFileSizeInBytes; }
From source file:siddur.solidtrust.classic.ClassicController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model, HttpSession session) throws Exception { //upload/*w w w.ja v a 2s .co m*/ log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); orders = persister.validateTitle(firstLine); //persist persister.parseAndSave(br, orders, persister); } finally { if (br != null) { br.close(); } } return "redirect:upload.html"; }
From source file:siddur.solidtrust.fault.FaultController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, @RequestParam("version") int v, Model model, HttpSession session) throws Exception { IFaultPersister persister = getPersister(v); //upload//w w w . j a va2s . com log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); orders = persister.validateTitle(firstLine); //persist persister.parseAndSave(br, orders, persister); } finally { if (br != null) { br.close(); } } return "redirect:upload.html"; }
From source file:siddur.solidtrust.newprice2.Newprice2Controller.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model, HttpSession session) throws IOException { //upload//w ww.j a va 2s . c o m log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } FileStatus fs = new FileStatus(); fs.setFile(temp); log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; String[] fields; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); fields = StringUtils.split(firstLine, ";"); ; orders = new int[fields.length]; for (int i = 0; i < orders.length; i++) { orders[i] = ArrayUtils.indexOf(FIELDS, fields[i].trim()); } //count while (br.readLine() != null) { fs.next(); } } finally { if (br != null) { br.close(); } } fs.flip(); log4j.info("Total rows: " + fs.getTotalRow()); //persist carService.saveCars(fs, orders, carService); return "redirect:/v2/upload.html"; }
From source file:ubic.gemma.web.controller.common.auditAndSecurity.FileUploadController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) { /*/*from ww w . ja va 2 s.c o m*/ * At this point, the DispatcherServlet has already dealt with the multipart file via the * CommonsMultipartMonitoredResolver. */ if (!(request instanceof MultipartHttpServletRequest)) { return null; } Map<String, Object> model = new HashMap<>(); if (request instanceof FailedMultipartHttpServletRequest) { String errorMessage = ((FailedMultipartHttpServletRequest) request).getErrorMessage(); model.put("success", false); model.put("error", errorMessage); } else { MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = mrequest.getFileMap(); if (fileMap.size() > 1) { FileUploadController.log.error("Attempted to upload multiple files, returning error"); model.put("success", false); model.put("error", "Sorry, can't upload more than one file at a time yet"); } for (String key : fileMap.keySet()) { MultipartFile multipartFile = fileMap.get(key); File copiedFile = null; try { copiedFile = FileUploadUtil.copyUploadedFile(multipartFile, request); FileUploadController.log.info("Uploaded file: " + copiedFile); model.put("success", true); model.put("localFile", StringEscapeUtils.escapeJava(copiedFile.getAbsolutePath())); model.put("originalFile", multipartFile.getOriginalFilename()); model.put("size", multipartFile.getSize()); } catch (Exception e) { FileUploadController.log.error("Error in upload: " + e.getMessage(), e); model.put("success", false); model.put("error", e.getMessage()); } if (copiedFile == null) { FileUploadController.log.error("Error in upload: unknown problem getting file"); model.put("success", false); model.put("error", "unknown problem getting file"); } } } return new ModelAndView(new JSONView("text/html; charset=utf-8"), model); }