List of usage examples for org.springframework.web.multipart MultipartHttpServletRequest getFileNames
Iterator<String> getFileNames();
From source file:com.github.cherimojava.orchidae.controller.PictureController.java
/** * uploads multiple files into the system for the current user * /*from w ww . j ava2s .co m*/ * @param request * request with pictures to store * @return {@link org.springframework.http.HttpStatus#CREATED} if the upload was successful or * {@link org.springframework.http.HttpStatus#OK} if some of the pictures couldn't be uploaded together with * information which pictures couldn't be uploaded * @since 1.0.0 */ @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<String> handleFileUpload(MultipartHttpServletRequest request) { List<String> badFiles = Lists.newArrayList(); User user = userUtil .getUser((String) SecurityContextHolder.getContext().getAuthentication().getPrincipal()); for (Iterator<String> it = request.getFileNames(); it.hasNext();) { MultipartFile file = request.getFile(it.next()); // Create uuid and Picture entity Picture picture = factory.create(Picture.class); picture.setUser(user); picture.setTitle(StringUtils.split(file.getOriginalFilename(), ".")[0]); picture.setId(generateId()); picture.setOriginalName(file.getOriginalFilename()); picture.setUploadDate(DateTime.now()); String type = StringUtils.substringAfterLast(file.getOriginalFilename(), "."); try { File storedPicture = fileUtil.getFileHandle(picture.getId()); // save picture file.transferTo(storedPicture); // read some some properties from it BufferedImage image = ImageIO.read(storedPicture); picture.setHeight(image.getHeight()); picture.setWidth(image.getWidth()); picture.setAccess(Access.PRIVATE);// TODO for now only private access createSmall(picture.getId(), image, type); LOG.info("Uploaded {} and assigned id {}", file.getOriginalFilename(), picture.getId()); checkBatch(picture, request); picture.save(); } catch (Exception e) { LOG.warn("failed to store picture", e); badFiles.add(file.getOriginalFilename()); } } if (badFiles.isEmpty()) { return new ResponseEntity<>("You successfully uploaded!", HttpStatus.CREATED); } else { return new ResponseEntity<>( "Could not upload all files. Failed to upload: " + Joiner.on(",").join(badFiles), HttpStatus.OK); } }
From source file:com.baidu.upload.controller.ImageController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody Map<String, Object> upload(MultipartHttpServletRequest request, HttpServletResponse response, Integer reqid) { log.debug("uploadPost called"); System.out.println("id" + reqid); //????//from ww w . java 2 s.c om Iterator<String> itr = request.getFileNames(); MultipartFile mpf; List<Image> list = new LinkedList<Image>(); InputStream is = null; List<File> newfiles = new ArrayList<File>(); while (itr.hasNext()) { mpf = request.getFile(itr.next()); //?uuid?? String newFilenameBase = UUID.randomUUID().toString(); //???? String originalFileExtension = mpf.getOriginalFilename() .substring(mpf.getOriginalFilename().lastIndexOf(".")); //??? String newFilename = newFilenameBase + originalFileExtension; //? //String storageDirectory = request.getSession().getServletContext().getRealPath("/")+"pic"; //fileUploadDirectory = storageDirectory; String storageDirectory = fileUploadDirectory; String contentType = mpf.getContentType(); // File newFile = new File(storageDirectory + "/" + newFilename); try { //?? is = mpf.getInputStream(); byte[] bytes = FileCopyUtils.copyToByteArray(is); // mpf.transferTo(newFile); // BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); //??uuid-thumbnail.png String thumbnailFilename = newFilenameBase + "-thumbnail.png"; // File thumbnailFile = new File(storageDirectory + "/" + thumbnailFilename); ImageIO.write(thumbnail, "png", thumbnailFile); //image Image image = new Image(); //?blob image.setImgblob(bytes); //image.setName(mpf.getOriginalFilename()); image.setName(newFilename); image.setThumbnailFilename(thumbnailFilename); image.setNewFilename(newFilename); image.setContentType(contentType); image.setSize(mpf.getSize()); image.setThumbnailSize(thumbnailFile.length()); //?id int id = this.imageService.findId(); image.setId(id); //url image.setUrl("../img/picture/" + image.getId() + ".do"); image.setThumbnailUrl("../img/thumbnail/" + image.getId() + ".do"); image.setDeleteUrl("../img/delete/" + image.getId() + ".do"); image.setDeleteType("DELETE"); //? image.setReqid(reqid); image = imageService.create(image); newfiles.add(newFile); //?? list.add(image); } catch (IOException e) { log.error("Could not upload file " + mpf.getOriginalFilename(), e); } finally { IOUtils.closeQuietly(is); } } Map<String, Object> files = new HashMap<String, Object>(); files.put("files", list); return files; }
From source file:gr.abiss.calipso.tiers.controller.IFilesModelController.java
@ApiOperation(value = "Update files", notes = "The files are saved using the parameter names of the multipart files contained in this request. " + "These are the field names of the form (like with normal parameters), not the original file names.") @RequestMapping(value = "{id}/files", method = { RequestMethod.POST }, headers = ("content-type=multipart/*"), produces = { "application/json", "application/xml" }) public default @ResponseBody T updateFiles(@PathVariable ID id, MultipartHttpServletRequest request, HttpServletResponse response) {//from w w w . j av a 2s .c o m Logger logger = LoggerFactory.getLogger(IFilesModelController.class); T entity = this.getService().findById(id); try { String basePath = new StringBuffer(this.getService().getDomainClass().getSimpleName()).append('/') .append(id).append('/').toString(); String propertyName; for (Iterator<String> iterator = request.getFileNames(); iterator.hasNext();) { // get the property name propertyName = iterator.next(); // verify the property exists Field fileField = GenericSpecifications.getField(this.getService().getDomainClass(), propertyName); if (fileField == null || !fileField.isAnnotationPresent(FilePersistence.class)) { throw new IllegalArgumentException( "No FilePersistence annotation found for member: " + propertyName); } // store the file and update the property URL String url = this.getFilePersistenceService().saveFile(fileField, request.getFile(propertyName), basePath + propertyName); BeanUtils.setProperty(entity, propertyName, url); } } catch (Exception e) { throw new RuntimeException("Failed to update files", e); } // return the updated entity return this.getService().update(entity); }
From source file:com.pantuo.service.impl.AttachmentServiceImpl.java
public String saveAttachmentSimple(HttpServletRequest request) throws BusinessException { StringBuffer r = new StringBuffer(); try {//from www . j a v a2s.com CustomMultipartResolver multipartResolver = new CustomMultipartResolver( request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { String path = request.getSession().getServletContext() .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", ""); MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile(iter.next()); if (file != null && !file.isEmpty()) { String oriFileName = file.getOriginalFilename(); if (StringUtils.isNoneBlank(oriFileName)) { String storeName = GlobalMethods .md5Encrypted((System.currentTimeMillis() + oriFileName).getBytes()); Pair<String, String> p = FileHelper.getUploadFileName(path, storeName += FileHelper.getFileExtension(oriFileName, true)); File localFile = new File(p.getLeft()); file.transferTo(localFile); if (r.length() == 0) { r.append(p.getRight()); } else { r.append(";" + p.getRight()); } } } } } return r.toString(); } catch (Exception e) { log.error("saveAttachmentSimple", e); throw new BusinessException("saveAttachment-error", e); } }
From source file:com.qcadoo.mes.cmmsMachineParts.controller.MachinePartMultiUploadController.java
@ResponseBody @RequestMapping(value = "/multiUploadFiles", method = RequestMethod.POST) public void upload(MultipartHttpServletRequest request, HttpServletResponse response) { Long part = Long.parseLong(request.getParameter("partId")); Entity technology = dataDefinitionService .get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT).get(part); DataDefinition attachmentDD = dataDefinitionService.get("cmmsMachineParts", "machinePartAttachment"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf = null;//w ww. ja va2s . co m while (itr.hasNext()) { mpf = request.getFile(itr.next()); String path = ""; try { path = fileService.upload(mpf); } catch (IOException e) { logger.error("Unable to upload attachment.", e); } if (exts.contains(Files.getFileExtension(path).toUpperCase())) { Entity atchment = attachmentDD.create(); atchment.setField(TechnologyAttachmentFields.ATTACHMENT, path); atchment.setField(TechnologyAttachmentFields.NAME, mpf.getOriginalFilename()); atchment.setField("product", technology); atchment.setField(TechnologyAttachmentFields.EXT, Files.getFileExtension(path)); BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext()); BigDecimal divider = new BigDecimal(1024, numberService.getMathContext()); BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP); atchment.setField(TechnologyAttachmentFields.SIZE, size); atchment = attachmentDD.save(atchment); atchment.isValid(); } } }
From source file:eionet.webq.web.controller.WebQProxyDelegation.java
/** * The method proxies multipart POST requests. If the request target is CDR envelope, then USerFile authorization info is used. * * @param uri the address to forward the request * @param fileId UserFile id stored in session * @param multipartRequest file part in multipart request * @return response from remote host/*from w w w . ja v a2 s. c om*/ * @throws URISyntaxException provide URI is incorrect * @throws IOException could not read file from request */ @RequestMapping(value = "/restProxyFileUpload", method = RequestMethod.POST, produces = "text/html;charset=utf-8") @ResponseBody public String restProxyFileUpload(@RequestParam("uri") String uri, @RequestParam int fileId, MultipartHttpServletRequest multipartRequest) throws URISyntaxException, IOException { UserFile file = userFileHelper.getUserFile(fileId, multipartRequest); if (!multipartRequest.getFileNames().hasNext()) { throw new IllegalArgumentException("File not found in multipart request."); } Map<String, String[]> parameters = multipartRequest.getParameterMap(); // limit request to one file String fileName = multipartRequest.getFileNames().next(); MultipartFile multipartFile = multipartRequest.getFile(fileName); HttpHeaders authorization = new HttpHeaders(); if (file != null && StringUtils.startsWith(uri, file.getEnvelope())) { authorization = envelopeService.getAuthorizationHeader(file); } HttpHeaders fileHeaders = new HttpHeaders(); fileHeaders.setContentDispositionFormData("file", multipartFile.getOriginalFilename()); fileHeaders.setContentType(MediaType.valueOf(multipartFile.getContentType())); MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>(); byte[] content = multipartFile.getBytes(); request.add("file", new HttpEntity<byte[]>(content, fileHeaders)); for (Map.Entry<String, String[]> parameter : parameters.entrySet()) { if (!parameter.getKey().equals("uri") && !parameter.getKey().equals("fileId") && !parameter.getKey().equals("sessionid") && !parameter.getKey().equals("restricted")) { request.add(parameter.getKey(), new HttpEntity<String>(StringUtils.defaultString(parameter.getValue()[0]))); } } HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>( request, authorization); LOGGER.info("/restProxyFileUpload [POST] uri=" + uri); return restTemplate.postForObject(uri, requestEntity, String.class); }
From source file:com.pantuo.service.impl.AttachmentServiceImpl.java
@Override public String savePayvoucher(HttpServletRequest request, String user_id, int main_id, JpaAttachment.Type file_type, String description) throws BusinessException { String result = ""; try {//from w w w.j av a 2s . com CustomMultipartResolver multipartResolver = new CustomMultipartResolver( request.getSession().getServletContext()); log.info("userid:{},main_id:{},file_type:{}", user_id, main_id, file_type); if (multipartResolver.isMultipart(request)) { String path = request.getSession().getServletContext() .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", ""); log.info("path=", path); MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile(iter.next()); if (file != null && !file.isEmpty()) { String oriFileName = file.getOriginalFilename(); String fn = file.getName(); if (StringUtils.isNoneBlank(oriFileName)) { String storeName = GlobalMethods .md5Encrypted((System.currentTimeMillis() + oriFileName).getBytes()); Pair<String, String> p = FileHelper.getUploadFileName(path, storeName += FileHelper.getFileExtension(oriFileName, true)); File localFile = new File(p.getLeft()); file.transferTo(localFile); AttachmentExample example = new AttachmentExample(); AttachmentExample.Criteria criteria = example.createCriteria(); criteria.andMainIdEqualTo(main_id); criteria.andUserIdEqualTo(user_id); criteria.andTypeEqualTo(JpaAttachment.Type.payvoucher.ordinal()); List<Attachment> attachments = attachmentMapper.selectByExample(example); if (attachments.size() > 0) { Attachment t = attachments.get(0); t.setUpdated(new Date()); t.setName(oriFileName); t.setUrl(p.getRight()); attachmentMapper.updateByPrimaryKey(t); result = p.getRight(); } else { Attachment t = new Attachment(); if (StringUtils.isNotBlank(description)) { t.setDescription(description); } t.setMainId(main_id); t.setType(file_type.ordinal()); t.setCreated(new Date()); t.setUpdated(t.getCreated()); t.setName(oriFileName); t.setUrl(p.getRight()); t.setUserId(user_id); attachmentMapper.insert(t); result = p.getRight(); } } } } } } catch (Exception e) { log.error("saveAttachment", e); throw new BusinessException("saveAttachment-error", e); } return result; }
From source file:com.pantuo.service.impl.AttachmentServiceImpl.java
public void saveAttachment(HttpServletRequest request, String user_id, int main_id, JpaAttachment.Type file_type, String description) throws BusinessException { try {//w ww.java 2 s .c o m CustomMultipartResolver multipartResolver = new CustomMultipartResolver( request.getSession().getServletContext()); log.info("userid:{},main_id:{},file_type:{}", user_id, main_id, file_type); if (multipartResolver.isMultipart(request)) { String path = request.getSession().getServletContext() .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", ""); MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile(iter.next()); if (file != null && !file.isEmpty()) { String oriFileName = file.getOriginalFilename(); String fn = file.getName(); if (StringUtils.isNoneBlank(oriFileName)) { String storeName = GlobalMethods .md5Encrypted((System.currentTimeMillis() + oriFileName).getBytes()); Pair<String, String> p = FileHelper.getUploadFileName(path, storeName += FileHelper.getFileExtension(oriFileName, true)); File localFile = new File(p.getLeft()); file.transferTo(localFile); AttachmentExample example = new AttachmentExample(); AttachmentExample.Criteria criteria = example.createCriteria(); criteria.andMainIdEqualTo(main_id); criteria.andUserIdEqualTo(user_id); criteria.andTypeEqualTo(JpaAttachment.Type.user_qualifi.ordinal()); List<Attachment> attachments = attachmentMapper.selectByExample(example); if (attachments.size() > 0) { Attachment t = attachments.get(0); t.setUpdated(new Date()); t.setName(oriFileName); t.setUrl(p.getRight()); attachmentMapper.updateByPrimaryKey(t); } else { Attachment t = new Attachment(); if (StringUtils.isNotBlank(description)) { t.setDescription(description); } t.setMainId(main_id); if (StringUtils.equals(fn, "licensefile")) { t.setType(JpaAttachment.Type.license.ordinal()); } else if (fn.indexOf("qua") != -1) { t.setType(JpaAttachment.Type.u_fj.ordinal()); } else if (StringUtils.equals(fn, "taxfile")) { t.setType(JpaAttachment.Type.tax.ordinal()); } else if (StringUtils.equals(fn, "taxpayerfile")) { t.setType(JpaAttachment.Type.taxpayer.ordinal()); } else if (StringUtils.equals(fn, "user_license")) { t.setType(JpaAttachment.Type.user_license.ordinal()); } else if (StringUtils.equals(fn, "user_code")) { t.setType(JpaAttachment.Type.user_code.ordinal()); } else if (StringUtils.equals(fn, "user_tax")) { t.setType(JpaAttachment.Type.user_tax.ordinal()); } else { t.setType(file_type.ordinal()); } t.setCreated(new Date()); t.setUpdated(t.getCreated()); t.setName(oriFileName); t.setUrl(p.getRight()); t.setUserId(user_id); attachmentMapper.insert(t); } } } } } } catch (Exception e) { log.error("saveAttachment", e); throw new BusinessException("saveAttachment-error", e); } }
From source file:com.pantuo.service.impl.AttachmentServiceImpl.java
public void updateAttachments(HttpServletRequest request, String user_id, int main_id, JpaAttachment.Type file_type, String description) throws BusinessException { try {//from ww w. ja v a2 s . com CustomMultipartResolver multipartResolver = new CustomMultipartResolver( request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { String path = request.getSession().getServletContext() .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", ""); MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile(iter.next()); if (file != null && !file.isEmpty()) { String oriFileName = file.getOriginalFilename(); String fn = file.getName(); if (StringUtils.isNoneBlank(oriFileName)) { String storeName = GlobalMethods .md5Encrypted((System.currentTimeMillis() + oriFileName).getBytes()); Pair<String, String> p = FileHelper.getUploadFileName(path, storeName += FileHelper.getFileExtension(oriFileName, true)); File localFile = new File(p.getLeft()); file.transferTo(localFile); AttachmentExample example = new AttachmentExample(); AttachmentExample.Criteria criteria = example.createCriteria(); criteria.andMainIdEqualTo(main_id); criteria.andUserIdEqualTo(user_id); List<Attachment> attachments = attachmentMapper.selectByExample(example); for (Attachment t : attachments) { if (StringUtils.equals(fn, "licensefile") && t.getType() == JpaAttachment.Type.license.ordinal()) { t.setUpdated(new Date()); t.setName(oriFileName); t.setUrl(p.getRight()); attachmentMapper.updateByPrimaryKey(t); } if (StringUtils.equals(fn, "taxfile") && t.getType() == JpaAttachment.Type.tax.ordinal()) { t.setUpdated(new Date()); t.setName(oriFileName); t.setUrl(p.getRight()); attachmentMapper.updateByPrimaryKey(t); } if (StringUtils.equals(fn, "taxpayerfile") && t.getType() == JpaAttachment.Type.taxpayer.ordinal()) { t.setUpdated(new Date()); t.setName(oriFileName); t.setUrl(p.getRight()); attachmentMapper.updateByPrimaryKey(t); } if (StringUtils.equals(fn, "user_license") && t.getType() == JpaAttachment.Type.user_license.ordinal()) { t.setUpdated(new Date()); t.setName(oriFileName); t.setUrl(p.getRight()); attachmentMapper.updateByPrimaryKey(t); } if (StringUtils.equals(fn, "user_tax") && t.getType() == JpaAttachment.Type.user_tax.ordinal()) { t.setUpdated(new Date()); t.setName(oriFileName); t.setUrl(p.getRight()); attachmentMapper.updateByPrimaryKey(t); } if (StringUtils.equals(fn, "user_code") && t.getType() == JpaAttachment.Type.user_code.ordinal()) { t.setUpdated(new Date()); t.setName(oriFileName); t.setUrl(p.getRight()); attachmentMapper.updateByPrimaryKey(t); } } } } } } } catch (Exception e) { log.error("saveAttachment", e); throw new BusinessException("saveAttachment-error", e); } }
From source file:com.qcadoo.mes.cmmsMachineParts.controller.MaintenanceEventMultiUploadController.java
@ResponseBody @RequestMapping(value = "/multiUploadFilesForEvent", method = RequestMethod.POST) public void upload(MultipartHttpServletRequest request, HttpServletResponse response) { Long eventId = Long.parseLong(request.getParameter("eventId")); Entity event = dataDefinitionService .get(CmmsMachinePartsConstants.PLUGIN_IDENTIFIER, CmmsMachinePartsConstants.MODEL_MAINTENANCE_EVENT) .get(eventId);/* w w w . j a v a 2 s.com*/ DataDefinition attachmentDD = dataDefinitionService.get("cmmsMachineParts", "eventAttachment"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf = null; while (itr.hasNext()) { mpf = request.getFile(itr.next()); String path = ""; try { path = fileService.upload(mpf); } catch (IOException e) { logger.error("Unable to upload attachment.", e); } if (exts.contains(Files.getFileExtension(path).toUpperCase())) { Entity atchment = attachmentDD.create(); atchment.setField(TechnologyAttachmentFields.ATTACHMENT, path); atchment.setField(TechnologyAttachmentFields.NAME, mpf.getOriginalFilename()); atchment.setField("maintenanceEvent", event); atchment.setField(TechnologyAttachmentFields.EXT, Files.getFileExtension(path)); BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext()); BigDecimal divider = new BigDecimal(1024, numberService.getMathContext()); BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP); atchment.setField(TechnologyAttachmentFields.SIZE, size); atchment = attachmentDD.save(atchment); atchment.isValid(); } } }