기본 콘텐츠로 건너뛰기

Java Spring File upload, download, delete

public List<Attach> upload(HttpServletRequest request, MultipartFile[] files, Integer fbnum) {
    String savePath = request.getServletContext().getRealPath("/WEB-INF/files");
    System.out.println("savePath:"+savePath);
    try {
        List<Attach> liAttach = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            Attach attach = new Attach();
            attach.setAname(files[i].getOriginalFilename());
            attach.setAsize(files[i].getSize());
            attach.setFbnum(fbnum);
            Attach save = attachRepository.save(attach);
            files[i].transferTo(new File(savePath + "/" + save.getAnum() + "_" + save.getAname()));
            liAttach.add(save);
        }
    return liAttach;
    } catch (Exception e) {
        System.err.println("파일저장 실패");
        //e.printStackTrace();
    }
    return null;
}

public ResponseEntity<Resource> donwload(HttpServletRequest request, String filepath) {
    String path = request.getServletContext().getRealPath("/WEB-INF/files");
    Resource resource = resourceLoader.getResource(path + filepath);
    String contentType = null;
    try {
        contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (contentType == null) {
        contentType = "application/octet-stream";
    }
    String filename = resource.getFilename();
    filename = filename.substring(filename.indexOf("_") + 1, filename.length());
    return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"").body(resource);
}

public boolean delete(HttpServletRequest request, Attach...attachs) {
    try {
        String path = request.getServletContext().getRealPath("/WEB-INF/files");
        System.out.println("path:"+path);
        for (int i = 0; i < attachs.length; i++) {
            attachRepository.deleteById(attachs[i].getAnum());
            new File(path + "/" + attachs[i].getAnum() + "_" + attachs[i].getAname()).delete();
        }
        return true;
    } catch(Exception e) {
        System.err.println("파일삭제 실패");
        e.printStackTrace();
    }
    return false;
}

이 블로그의 인기 게시물