Example #1
0
  /**
   * 사용자 첨부파일로 업로드한다
   *
   * <p>when 이슈나 글, 코멘트등에서 파일을 첨부하기 전에 먼저 업로드
   *
   * <p>멀티파트 폼데이터로 파일 업로드 요청을 받아서 서버에 파일 저장을 시도하고 만약 이미 같은 파일이 서버내에 globally 존재한다면 200OK로 응답 존재하지 않는
   * 파일이라면 201 created로 응답
   *
   * <p>요청에 첨부파일이 없는 것으로 보일때는 400 Bad Request로 응답 업로더가 익명 사용자일 경우에는 403 Forbidden 으로 응답
   *
   * <p>업로드된 파일은 그 파일을 업로드한 사용자에게 첨부된 상태가 된다. 이후 {@link Attachment#moveAll(models.resource.Resource,
   * models.resource.Resource)} 등의 메소드를 사용해서 사용자의 첨부를 이슈 등의 다른 리소스로 옮길 수 있다.
   *
   * @return 생성된 파일의 메타데이터를 JSON 타입으로 반환하는 응답
   * @throws NoSuchAlgorithmException
   * @throws IOException
   */
  public static Result uploadFile() throws NoSuchAlgorithmException, IOException {
    // Get the file from request.
    FilePart filePart = request().body().asMultipartFormData().getFile("filePath");
    if (filePart == null) {
      return badRequest();
    }
    File file = filePart.getFile();

    User uploader = UserApp.currentUser();

    // Anonymous cannot upload a file.
    if (uploader.isAnonymous()) {
      return forbidden();
    }

    // Attach the file to the user who upload it.
    Attachment attach = new Attachment();
    boolean isCreated = attach.store(file, filePart.getFilename(), uploader.asResource());

    // The request has been fulfilled and resulted in a new resource being
    // created. The newly created resource can be referenced by the URI(s)
    // returned in the entity of the response, with the most specific URI
    // for the resource given by a Location header field.
    // -- RFC 2616, 10.2.2. 201 Created
    String url = routes.AttachmentApp.getFile(attach.id).url();
    response().setHeader("Location", url);

    // The entity format is specified by the media type given in the
    // Content-Type header field. -- RFC 2616, 10.2.2. 201 Created
    // While upload a file using Internet Explorer, if the response is not in
    // text/html, the browser will prompt the user to download it as a file.
    // To avoid this, if application/json is not acceptable by client, the
    // Content-Type field of response is set to "text/html". But, ACTUALLY
    // IT WILL BE SEND IN JSON!
    List<MediaRange> accepts = request().acceptedTypes();
    String contentType = request().accepts("application/json") ? "application/json" : "text/html";
    response().setHeader("Content-Type", contentType);

    // The response SHOULD include an entity containing a list of resource
    // characteristics and location(s) from which the user or user agent can
    // choose the one most appropriate. -- RFC 2616, 10.2.2. 201 Created
    Map<String, String> fileInfo = new HashMap<String, String>();
    fileInfo.put("id", attach.id.toString());
    fileInfo.put("mimeType", attach.mimeType);
    fileInfo.put("name", attach.name);
    fileInfo.put("url", url);
    fileInfo.put("size", attach.size.toString());
    JsonNode responseBody = toJson(fileInfo);

    if (isCreated) {
      // If an attachment has been created - it does NOT mean that
      // a file is created in the filesystem - return 201 Created.
      return created(responseBody);
    } else {
      // If the attachment already exists, return 200 OK.
      // Why not 204? -- Because 204 doesn't allow that response has body,
      // so we cannot tell what is same with the file you try to add.
      return ok(responseBody);
    }
  }
Example #2
0
  /**
   * 첨부파일의 메타데이터를 가져온다.
   *
   * @param attach 첨부
   * @return 메타데이터를 맵으로
   */
  private static Map<String, String> extractFileMetaDataFromAttachementAsMap(Attachment attach) {
    Map<String, String> metadata = new HashMap<String, String>();

    metadata.put("id", attach.id.toString());
    metadata.put("mimeType", attach.mimeType);
    metadata.put("name", attach.name);
    metadata.put("url", routes.AttachmentApp.getFile(attach.id).url());
    metadata.put("size", attach.size.toString());

    return metadata;
  }
Example #3
0
  /**
   * 사용자 정보 수정
   *
   * @return
   */
  public static Result editUserInfo() {
    Form<User> userForm = new Form<>(User.class).bindFromRequest("name", "email");
    String newEmail = userForm.data().get("email");
    String newName = userForm.data().get("name");
    User user = UserApp.currentUser();

    if (StringUtils.isEmpty(newEmail)) {
      userForm.reject("email", "user.wrongEmail.alert");
    } else {
      if (!StringUtils.equals(user.email, newEmail) && User.isEmailExist(newEmail)) {
        userForm.reject("email", "user.email.duplicate");
      }
    }

    if (userForm.error("email") != null) {
      flash(Constants.WARNING, userForm.error("email").message());
      return badRequest(edit.render(userForm, user));
    }
    user.email = newEmail;
    user.name = newName;

    try {
      Long avatarId = Long.valueOf(userForm.data().get("avatarId"));
      if (avatarId != null) {
        Attachment attachment = Attachment.find.byId(avatarId);
        String primary = attachment.mimeType.split("/")[0].toLowerCase();
        if (primary.equals("image")) {
          Attachment.deleteAll(currentUser().avatarAsResource());
          attachment.moveTo(currentUser().avatarAsResource());
          user.avatarUrl = routes.AttachmentApp.getFile(attachment.id).url();
        }
      }
    } catch (NumberFormatException e) {
    }

    user.update();
    return redirect(
        routes.UserApp.userInfo(user.loginId, DEFAULT_GROUP, DAYS_AGO, DEFAULT_SELECTED_TAB));
  }