@RequestMapping(method = RequestMethod.POST, value = "saveImg") public void uploadBrandImg( @RequestParam("imgFile") CommonsMultipartFile file, HttpServletResponse response) { if (file.getSize() > 0) { // 定义允许上传的文件扩展名 HashMap<String, String> extMap = new HashMap<String, String>(); extMap.put("image", "gif,jpg,jpeg,png,bmp"); // 最大文件大小 long maxSize = 102400; response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = null; try { pw = response.getWriter(); String fileName = file.getOriginalFilename(); if (file.getSize() > maxSize) { // 检查文件大小 pw.print(getError("上传文件大小超过限制。")); return; } String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); // 检查扩展名 if (!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)) { pw.print(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get("image") + "格式。")); return; } List<String> urls = HttpCilient.uploadFileService(file.getInputStream(), fileName, null); StringBuilder fullUrl = new StringBuilder(); for (String url : urls) { fullUrl.append(PropertyUtils.getRandomProperty("imgGetUrl") + url + ","); } pw.print(getRight(fullUrl.substring(0, fullUrl.length() - 1))); } catch (Exception e) { logger.info("上传文件失败!", e); if (pw != null) { pw.println(getError("上传文件失败。")); } } finally { if (pw != null) { pw.close(); } } } }
@ResponseBody @RequestMapping(value = "/admin/upload.ajax", method = RequestMethod.POST) public ResponseEntity<byte[]> upload( @RequestParam("restaurantId") String restaurantId, @RequestParam("file") CommonsMultipartFile file) throws Exception { Map<String, Object> model = new HashMap<String, Object>(); try { S3Object object = new S3Object(basePath + "/" + restaurantId); object.setDataInputStream(file.getInputStream()); object.setContentLength(file.getSize()); object.setContentType(file.getContentType()); S3Bucket bucket = s3Service.getBucket(bucketName); s3Service.putObject(bucket, object); Restaurant restaurant = restaurantRepository.findByRestaurantId(restaurantId); restaurant.setHasUploadedImage(true); restaurantRepository.saveRestaurant(restaurant); model.put("success", true); } catch (Exception ex) { LOGGER.error("", ex); model.put("success", false); model.put("message", ex.getMessage()); } String json = jsonUtils.serializeAndEscape(model); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_HTML); headers.setCacheControl("no-cache"); return new ResponseEntity<byte[]>(json.getBytes("utf-8"), headers, HttpStatus.OK); }
@Override public boolean isValid(CommonsMultipartFile value, ConstraintValidatorContext context) { boolean isValid = true; if (value == null) { isValid = !constraintAnnotation.required(); } else if (constraintAnnotation.required() && value.getSize() == 0) { isValid = false; } else if (constraintAnnotation.maxSize() >= 0 && value.getSize() > constraintAnnotation.maxSize()) { isValid = false; } return isValid; }
public GBLAttachment(CommonsMultipartFile commonsMultipartFile) { super(); this.commonsMultipartFile = commonsMultipartFile; setFileName(commonsMultipartFile.getOriginalFilename()); setFileExtension(getExtension(commonsMultipartFile.getOriginalFilename())); setMimeType(commonsMultipartFile.getContentType()); setFileSize(commonsMultipartFile.getSize()); }
public void validateSelectFileStep(ValidationContext context) { MessageContext messageContext = context.getMessageContext(); if (file == null || file.getSize() <= 0) { messageContext.addMessage( new MessageBuilder() .error() .source("file") .code("errors.importexport.mandatory_file") .build()); } }
/** multipart에 대한 parsing을 처리한다. */ @SuppressWarnings("unchecked") @Override protected MultipartParsingResult parseFileItems(List fileItems, String encoding) { Map multipartFiles = new HashMap(); Map multipartParameters = new HashMap(); // Extract multipart files and multipart parameters. for (Iterator it = fileItems.iterator(); it.hasNext(); ) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { String value = null; if (encoding != null) { try { value = fileItem.getString(encoding); } catch (UnsupportedEncodingException ex) { if (logger.isWarnEnabled()) { logger.warn( "Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + encoding + "': using platform default"); } value = fileItem.getString(); } } else { value = fileItem.getString(); } String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] {value}); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } } else { if (fileItem.getSize() > 0) { // multipart file field CommonsMultipartFile file = new CommonsMultipartFile(fileItem); if (multipartFiles.put(fileItem.getName(), file) != null) { // CHANGED!! throw new MultipartException( "Multiple files for field name [" + file.getName() + "] found - not supported by MultipartResolver"); } if (logger.isDebugEnabled()) { logger.debug( "Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription()); } } } } return new MultipartParsingResult(multipartFiles, multipartParameters); }
@RequestMapping(method = RequestMethod.POST) public String onSubmit(FileUpload fileUpload, BindingResult errors, HttpServletRequest request) throws Exception { if (validator != null) { // validator is null during testing validator.validate(fileUpload, errors); if (errors.hasErrors()) { return "uploadForm"; } } // validate a file was entered if (fileUpload.getFile().length == 0) { Object[] args = new Object[] {getText("uploadForm.file", request.getLocale())}; errors.rejectValue("file", "errors.required", args, "File"); return "uploadForm"; } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file"); // the directory to upload to String uploadDir = getServletContext().getRealPath("/resources") + "/" + request.getRemoteUser() + "/"; // Create the directory if it doesn't exist File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); } // retrieve the file data InputStream stream = file.getInputStream(); // write the file to the file specified OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename()); int bytesRead; byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); // close the stream stream.close(); // place the data into the request for retrieval on next page request.setAttribute("friendlyName", fileUpload.getName()); request.setAttribute("fileName", file.getOriginalFilename()); request.setAttribute("contentType", file.getContentType()); request.setAttribute("size", file.getSize() + " bytes"); request.setAttribute( "location", dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename()); String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/"; request.setAttribute("link", link + file.getOriginalFilename()); return getSuccessView(); }