@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);
  }
Пример #2
0
 public static File resizeUploadImage(CommonsMultipartFile file, int width, int height)
     throws IOException {
   File finalFile = File.createTempFile(TokenGenerator.generateToken(), "");
   BufferedImage originalImage = ImageIO.read(file.getInputStream());
   BufferedImage resizedImage = new BufferedImage(width, height, originalImage.getType());
   Graphics2D g = resizedImage.createGraphics();
   g.drawImage(originalImage, 0, 0, width, height, null);
   g.dispose();
   ImageIO.write(resizedImage, "png", finalFile);
   return finalFile;
 }
Пример #3
0
  @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();
        }
      }
    }
  }
  @RequestMapping("/upload/file")
  public String fileupload(@RequestParam("aaa") CommonsMultipartFile file, HttpServletRequest res) {

    System.out.println("File Name ===============" + file.getOriginalFilename());
    if (!file.isEmpty()) {
      try {
        FileOutputStream fos =
            new FileOutputStream("D:\\" + file.getOriginalFilename() + "_" + new Date().getTime());
        InputStream in = file.getInputStream();
        int b = 0;
        while ((b = in.read()) != -1) {
          fos.write(b);
        }
        fos.flush();
        fos.close();
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return "success";
  }
Пример #5
0
  @RequestMapping("uploadFile.do")
  public @ResponseBody Object uploadObject(
      @RequestParam("source") CommonsMultipartFile mFile,
      @ModelAttribute UploadSource uploadSource) {
    // System.out.println(mFile);
    try {
      // Set the expired time to one hour later.
      uploadSource.setInputStream(mFile.getInputStream());

      ObjectMetadata objectMetaData = new ObjectMetadata();
      objectMetaData.setContentType(mFile.getContentType());
      objectMetaData.setContentLength(mFile.getFileItem().getSize());

      uploadSource.setObjectMetaData(objectMetaData);

      ossService.uploadObject(uploadSource);
      // Thread.sleep(2000);

      return genSuccessResponse("", null);
    } catch (Exception e) {
      e.printStackTrace();
      return genFailureResponse(e.getMessage());
    }
  }
  @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();
  }