개인 자료 정리 홈페이지 입니다.

Note > 스프링 부트 파일첨부, Ui Dropzone.js스프링부트 파일 첨부 처리 부분

By a3040, Published on Invalid Date

Controller 작성


@Controller
public class FileUploadController {

...
@Autowired
    private final StorageService storageService;


    
    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }


    @PostMapping("/common/fileform/upload")
    @ResponseBody
    public ResponseEntity<List<Attachment>> uploadFiles(@RequestParam("file") List<MultipartFile> files) {
        int owner_seq = 1;
        List<Attachment> attachments = new ArrayList<Attachment>();
        for (MultipartFile file : files) { 
            
            // 업로드된 파일 저장
            try { 
...
                // 파일 정보 저장
                storageService.store(file);  
  
            } catch (IOException e) {
                e.printStackTrace();
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        return ResponseEntity.ok(attachments);
    }


파일첨부 저장을위한 서비스 부분

@Service
public class StorageService { 
    @Value("${upload.folder}")
    private String uploadFolder;
    
    private Path rootLocation;


    public StorageService() {    
        this.rootLocation = null;
    }
    
    @PostConstruct
    public void init() {
        this.rootLocation = Paths.get(uploadFolder);
    }


    private String getExtension(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String fileExtension = "";
        if (fileName != null && fileName.contains(".")) {
            fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        }
        return fileExtension;
    }


    void store(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extension = this.getExtension(file);


        String filename = UUID.randomUUID().toString() + "." + extension;

        byte[] bytes = file.getBytes();
        Path filePath = Paths.get(uploadFolder + File.separator + filename);
        Files.write(filePath, bytes);

    }


    // Stream<Path> loadAll();


    public Path load(String filename) {
        return rootLocation.resolve(filename);
    }


    public Resource loadAsResource(String filename) throws MalformedURLException {
        Path file = rootLocation.resolve(filename);
        Resource resource = null;
        resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        }
        return resource;
    }


    public void delete(String filename) throws IOException {
        Path file = load(filename);
        Files.delete(file);
    }


    // void deleteAll();


}


설정을 위한 resources/application.properties 부분


upload.folder=C:\\Users\\H......3040\\upload
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
Note > vscode에서 react debugger 설정설정하기

By a3040, Published on Invalid Date

프로젝트 폴더/.vscode/launch.json 에

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "msedge",
      "request": "launch",
      "name": "Launch Edge against localhost",
      "url": "http://localhost:3000",
      "webRoot": "${workspaceFolder}"
    }
  ]
}


내용을 추가 하거나 launch.json파일을 visual studio code에서 열면있는 "add configureation" 버튼를 눌러서 생성합니다.

저 참조위치가면 영상이 있습니다.


이후 프로젝트에서 react를 실행 합니다.

npm start

그리고 나서 vscode에서 방금 설정한 "Launch Edge against localhost"를 실행합니다.


새창이 띄면서 react가 실행된 창이 보입니다.


"url": "http://localhost:3000",  이부분의 포트나 위치는 npm start 에서설정한 포트나 내가 보고 싶은 페이지 주소입니다.
"url": "http://localhost:8080/Memo",


Note > 스프링시큐리티 jwt 적용하기jwt토큰을 이용한 권한 확인 필터

By a3040, Published on Invalid Date

SecurityFilterChain에 jwt토큰 관련 설정을 추가해서 권한에 따라 접근을 허가합니다.


@Component
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {


    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String authToken = extractAuthTokenFromRequest(request);
        if (authToken != null) {
            String username = jwtTokenUtil.getUsernameFromToken(authToken);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = jwtUserDetailsService.loadUserByJwtToken(authToken);
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }


    private String extractAuthTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7, bearerToken.length());
        }
        return null;
    }
}