Skip to content
Merged

Step6 #145

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 14 additions & 1 deletion src/main/java/codesquad/domain/Issue.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,17 @@ public class Issue extends AbstractEntity {
@JoinColumn(foreignKey = @ForeignKey(name = "fk_issue_assignee"))
private User assignee;

@OneToMany
@OneToMany(mappedBy = "issue")
@Where(clause = "deleted = false")
@JsonIgnore
@OrderBy("id ASC")
private List<Answer> answers = new ArrayList<>();

@OneToMany(mappedBy = "issue")
@JsonIgnore
@OrderBy("id ASC")
private List<Multipart> multiparts = new ArrayList<>();

private boolean deleted = false;

public Issue() {
Expand Down Expand Up @@ -132,6 +137,14 @@ public void setLabel(Label label) {
this.label = label;
}

public List<Multipart> getMultiparts() {
return multiparts;
}

public void setMultiparts(List<Multipart> multiparts) {
this.multiparts = multiparts;
}

public void update(User loginUser, Issue toIssue) {
if (!matchWriter(loginUser)) {
throw new UnAuthorizedException();
Expand Down
79 changes: 79 additions & 0 deletions src/main/java/codesquad/domain/Multipart.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package codesquad.domain;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import support.domain.AbstractEntity;

import javax.persistence.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import static org.slf4j.LoggerFactory.getLogger;

@Entity
public class Multipart extends AbstractEntity {
private static final Logger log = getLogger(Multipart.class);

@ManyToOne
@JoinColumn(foreignKey = @ForeignKey(name = "fk_multipart_writer"))
private User writer;

@ManyToOne
@JoinColumn(foreignKey = @ForeignKey(name = "fk_multipart_issue"))
private Issue issue;

@Column
private String originalFilename;

@Column
private String saveName;

private String uploadPath;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 설정이 정상적으로 동작하나?
의도한데로 동작하는지 값을 출력해 본다.


public Multipart() {
}

public Multipart(User user, Issue issue, String file, String uploadPath) {
this.writer = user;
this.issue = issue;
this.originalFilename = file;
this.saveName = UUID.randomUUID() + "_" + file;
this.uploadPath = uploadPath;
}

public User getWriter() {
return writer;
}

public String getOriginalFilename() {
return originalFilename;
}

public String getSaveName() {
return saveName;
}

public String getUploadPath() {
return uploadPath;
}

public Issue getIssue() {
return issue;
}

public void setIssue(Issue issue) {
this.issue = issue;
}

public Path add(User user, MultipartFile file) throws IOException {
byte[] bytes = file.getBytes();
Path path = Paths.get(uploadPath + saveName);
log.debug("path :~~~~~ {}", path.toString());
return Files.write(path, bytes);
}
}
9 changes: 9 additions & 0 deletions src/main/java/codesquad/domain/MultipartRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package codesquad.domain;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface MultipartRepository extends JpaRepository<Multipart, Long> {

}
3 changes: 3 additions & 0 deletions src/main/java/codesquad/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import support.domain.AbstractEntity;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.validation.constraints.Size;
import java.util.Objects;
Expand All @@ -27,6 +28,8 @@ public class User extends AbstractEntity {
@Column(nullable = false, length = 20)
private String name;



public User() {
}

Expand Down
1 change: 1 addition & 0 deletions src/main/java/codesquad/service/IssueService.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public class IssueService {
@Resource(name = "deleteHistoryService")
private DeleteHistoryService deleteHistoryService;


public Issue add(User user, IssueDto issueDto) {
issueDto.writeBy(user);
return issueRepository.save(issueDto._toIssue());
Expand Down
51 changes: 51 additions & 0 deletions src/main/java/codesquad/service/MultipartFileService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package codesquad.service;

import codesquad.domain.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

import static org.slf4j.LoggerFactory.getLogger;

@Service
public class MultipartFileService {
private static final Logger log = getLogger(MultipartFileService.class);
@Resource(name = "multipartRepository")
private MultipartRepository multipartRepository;

@Resource(name = "issueRepository")
private IssueRepository issueRepository;

@Value("${value.from.file}")
private String uploadPath;

@Transactional
public Multipart add(User user, long issueId, MultipartFile file) throws IOException {
Issue issue = issueRepository.findById(issueId).orElseThrow(UnknownError::new);
Multipart multipart = new Multipart(user, issue, file.getOriginalFilename(), uploadPath);
Path path = multipart.add(user, file);
file.transferTo(path);
return multipartRepository.save(multipart);
}

public List<Multipart> findAll() {
return multipartRepository.findAll();
}

// public List<Multipart> findByIssueId(long issueId) {
// return multipartRepository.(issueId);
// }

public String findPath(long id) {
Multipart multipart = multipartRepository.findById(id).orElseThrow(UnknownError::new);
return multipart.getUploadPath() + multipart.getSaveName();
}
}
5 changes: 2 additions & 3 deletions src/main/java/codesquad/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public User add(UserDto userDto) {

@Transactional
public User update(User loginUser, long id, UserDto updatedUser) {
User original = findById(loginUser, id);
User original = findById(id);
original.update(loginUser, updatedUser._toUser());
return userRepository.save(original);
}
Expand All @@ -48,9 +48,8 @@ public User findById(String userId) {
return userRepository.findByUserId(userId).orElseThrow(UnAuthorizedException::new);
}

public User findById(User loginUser, long id) {
public User findById(long id) {
return userRepository.findById(id)
.filter(user -> user.equals(loginUser))
.orElseThrow(UnAuthorizedException::new);
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/codesquad/web/ApiUserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public ResponseEntity<Void> create(@Valid @RequestBody UserDto user) {

@GetMapping("/{id}")
public UserDto show(@LoginUser User loginUser, @PathVariable long id) {
User user = userService.findById(loginUser, id);
User user = userService.findById(id);
return user._toUserDto();
}

Expand Down
61 changes: 61 additions & 0 deletions src/main/java/codesquad/web/AttatchmentController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package codesquad.web;

import codesquad.domain.User;
import codesquad.security.LoginUser;
import codesquad.service.MultipartFileService;
import org.slf4j.Logger;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.naming.CannotProceedException;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import static org.slf4j.LoggerFactory.getLogger;

@Controller
@RequestMapping("/attachments")
public class AttatchmentController {
private static final Logger log = getLogger(AttatchmentController.class);

@Resource(name = "multipartFileService")
private MultipartFileService multipartFileService;

@PostMapping("/{issueId}")
public String upload(@LoginUser User user, @PathVariable long issueId, MultipartFile file, Model model) throws Exception {
if (file.isEmpty()) {
throw new CannotProceedException();
}
multipartFileService.add(user, issueId, file);
return "redirect:/issues/{issueId}";
}

@GetMapping("/{id}")
public ResponseEntity<FileSystemResource> download(@PathVariable long id) throws IOException {
String saveName = multipartFileService.findPath(id);
Path path = Paths.get(saveName);
FileSystemResource resource = new FileSystemResource(path);

log.debug("~~~~~~~~1!!{}", saveName);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_XML);
headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + saveName);
headers.setContentLength(resource.contentLength());
log.debug("!!!@#!@# {}", headers);
return new ResponseEntity<FileSystemResource>(resource, headers, HttpStatus.OK);
}
}
4 changes: 3 additions & 1 deletion src/main/java/codesquad/web/IssueController.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ public class IssueController {
@Resource(name = "answerService")
private AnswerService answerService;

@Resource(name = "multipartFileService")
private MultipartFileService multipartFileService;

@GetMapping("")
public String createIssue(@LoginUser User user) {
return "issue/form";
Expand All @@ -54,7 +57,6 @@ public String showDetail(@PathVariable Long id, Model model) {
model.addAttribute("milestones", milestoneService.findAll());
model.addAttribute("labels", labelService.findAll());
model.addAttribute("assignees", userService.findAll());
model.addAttribute("answers", answerService.findAll());
return "issue/show";
}

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/codesquad/web/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ public String create(UserDto userDto) {
public String updateForm(@LoginUser User loginUser, @PathVariable long id, Model model) {
log.debug("LoginUser : {}", loginUser);
log.debug("login id : {}", id);
log.debug("user test :",userService.findById(loginUser, id));
log.debug("user test :",userService.findById(id));

model.addAttribute("user", userService.findById(loginUser, id));
model.addAttribute("user", userService.findById(id));
return "/user/updateForm";
}

Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ handlebars.cache=false
handlebars.expose-session-attributes=true
spring.main.allow-bean-definition-overriding=true

value.from.file=C:\\Users\\User\\Desktop\\fileUpload\\;
spring.servlet.multipart.max-file-size=15MB
5 changes: 3 additions & 2 deletions src/main/resources/import.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
INSERT INTO user (id, user_id, password, name) values (1, 'kuro', 'eogks369', 'kuro');
INSERT INTO user (id, user_id, password, name) values (2, 'dsoop', 'eogks369', 'daesoop');
INSERT INTO user (id, user_id, password, name) values (1, 'kuro', 'test', 'kuro');
INSERT INTO user (id, user_id, password, name) values (2, 'cmich8869', 'test', 'Myoungeun');
INSERT INTO user (id, user_id, password, name) values (3, 'dsoop', 'test', 'daesoop');

INSERT INTO issue (id, subject, comment, deleted, writer_id) values (1, 'this is first issue', 'this is soop first comment test', false, 1);
INSERT INTO issue (id, subject, comment, deleted, writer_id) values (2, 'this is second issue', 'this is soop second comment test', false, 1);
Expand Down
3 changes: 1 addition & 2 deletions src/main/resources/static/js/comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ function comment(e) {
console.log("커밋 생성중");

var queryString = $(".comments-write").serialize();
// var queryString = jQuery("daesoop");
console.log(queryString);

var url = $(".comments-write").attr("action");
console.log(url);



$.ajax({
type : 'post',
url : url,
Expand Down
24 changes: 22 additions & 2 deletions src/main/resources/templates/issue/show.html
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,28 @@ <h2 class="mdl-card__title-text">{{subject}}</h2>

<!--
start -->
{{#multiparts}}
<div class="comment mdl-color-text--grey-700">
<header class="comment__header">
<img class="comment__avatar2" height="48" width="48" src="https://avatars2.githubusercontent.com/u/520500?v=3&s=140" alt="{{writer.name}}">
<div class="comment__author">
<strong> <a>{{writer.name}}</a></strong>
<div>upload file <a href="/attachments/{{id}}">[{{originalFilename}}]</a></div>
<span>on {{createDate}}</span>
</div>
</header>
<div>
<ul class="article-util-list" style="display: inline-block;">
<li style="display: inline-block;">
<a class="delete-comment" href="/api/issues/{{issue.id}}/answers/{{id}}">삭제</a>
</li>
</ul>
</div>
<hr>
{{/multiparts}}
{{#answers}}
<div class="comment mdl-color-text--grey-700 answer-form">

<header class="comment__header">
<img class="comment__avatar2" height="48" width="48"
src="https://avatars2.githubusercontent.com/u/520500?v=3&s=140" alt="javajigi">
Expand Down Expand Up @@ -113,7 +133,7 @@ <h2 class="mdl-card__title-text">{{subject}}</h2>

<!-- comments end -->
</div>
<form action="/api/issues/{{id}}/comments" enctype="multipart/form-data" method="POST">
<form action="/attachments/{{id}}" enctype="multipart/form-data" method="POST">
<div style="margin:10px;">
<input type="file" name="file" id="file"/>
<button class="mdl-button" type="submit">upload file</button>
Expand All @@ -133,7 +153,7 @@ <h2 class="mdl-card__title-text">{{subject}}</h2>
</div>
</div>
</div>

</div>
{{/issue}}

<script type="text/template" id="commentTemplate">
Expand Down
Loading