inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링 DB 2편 - 데이터 접근 활용 기술

프로젝트 구조 설명2 - 설정

spring-mybatis 이미지 업로드 관련 NullPointerException 에러

1016

David Byun

작성한 질문수 5

0

안녕하세요!

수업 듣다가 Mybatis로 이미지 업로드 해보려는데, 실패해서요 조언 좀 듣고 싶습니다.

아래 코드에서 fileData.setFilePath가 Null 값으로 나오는데 왜그런걸까요 ? ㅠㅠ

java.lang.NullPointerException: null

com.restapi.bin.service.FileUploadDownloadService.uploadImageToFileSystem(FileUploadDownloadService.java:29) ~[main/:na]

@Data
public class FileData {
    private Long id;
    private String name;
    private String fileType;
    private String filePath;



    public FileData(Long id, String name, String fileType, String filePath) {
        this.id = id;
        this.name = name;
        this.fileType = fileType;
        this.filePath = filePath;
    }


}
@Service
@Slf4j
public class FileUploadDownloadService {
    @Autowired
    private FileDataMapper mapper;

    private static FileData fileData;

    private final String FOLDER_PATH = "/Users/david/Downloads/image/";

    public String uploadImageToFileSystem(MultipartFile file) throws IOException {

        String filePath = FOLDER_PATH + file.getOriginalFilename();
        log.info("file Path={}", filePath);
        fileData.setFilePath(filePath);
        fileData.setName(file.getOriginalFilename());
        fileData.setFileType(file.getContentType());
        log.info("fileData={}", fileData);
        mapper.insert(fileData);
        log.info("fileData={}/{}/{}", fileData.getFileType(), fileData.getName(), fileData.getFilePath());
        file.transferTo(new File(filePath));
        return null;
    }

    public byte[] downloadImageFromFileSystem(String fileName) throws IOException {
        Optional<FileData> dbImageData = mapper.findByFile(fileName);

        //이미지가 저장된 파일을 가져옴 > 바이트배열로 변환 > 서비스에서 다시 반환하여 얻음
        String filePath = dbImageData.get().getFilePath();
        byte[] images = Files.readAllBytes(new File(filePath).toPath());
        return images;
    }
}

spring mybatis

답변 1

1

OMG

안녕하세요. David Byun님, 공식 서포터즈 OMG입니다.
.

강의 코드 기반이 아닌 것 같고, 코드도 일부이기 때문에 도움을 드릴 수 있는 부분이 많이 한정되어 있는 점 참고 부탁드립니다.

@Data
public class FileData {
    private Long id;
    private String name;
    private String fileType;
    private String filePath;
    
    // 기본 생성자 추가
    public FileData() {
        
    }


    public FileData(Long id, String name, String fileType, String filePath) {
        this.id = id;
        this.name = name;
        this.fileType = fileType;
        this.filePath = filePath;
    }


}
@Service
@Slf4j
public class FileUploadDownloadService {
    @Autowired
    private FileDataMapper mapper;

    

    private final String FOLDER_PATH = "/Users/david/Downloads/image/";

    public String uploadImageToFileSystem(MultipartFile file) throws IOException {
        FileData fileData = new FileData(); // 인스턴스 생성

        String filePath = FOLDER_PATH + file.getOriginalFilename();
        log.info("file Path={}", filePath);
        fileData.setFilePath(filePath);
        fileData.setName(file.getOriginalFilename());
        fileData.setFileType(file.getContentType());
        log.info("fileData={}", fileData);
        mapper.insert(fileData);
        log.info("fileData={}/{}/{}", fileData.getFileType(), fileData.getName(), fileData.getFilePath());
        file.transferTo(new File(filePath));
        return null;
    }

    public byte[] downloadImageFromFileSystem(String fileName) throws IOException {
        Optional<FileData> dbImageData = mapper.findByFile(fileName);

        
        String filePath = dbImageData.get().getFilePath();
        byte[] images = Files.readAllBytes(new File(filePath).toPath());
        return images;
    }
}

추가된 2개의 주석 내용처럼 (1) 기본생성자를 생성 (2) FileData를 지역변수로 변경

2개를 변경해서 확인해볼 것 같습니다.

이렇게 수정하면 해결 될 것 같지만 해당 이유로 해결되지 않는다면 도움을 드리고 싶어도 정보가 부족하고 첨부한 코드 외의 코드가 어떻게 구성되어있는지 확인에 어려움이 있을 수 있어 더 이상 도움을 드리기 힘들 것 같습니다.


.
감사합니다.

0

David Byun

답을 늦게 확인했네요 감사합니다! OMG

설정 정보 없이 임베디드 데이터베이스 생성

0

17

1

RepositoryTest의 패키지 위치가 domain인 이유

0

39

2

REQUIRES_NEW 해결 방법에 대해서 질문있습니다!!

0

32

1

update()에 사용하는 setter 질문드립니다.

0

49

1

SQL 중심적 개발의 문제점에 대한 질문

0

79

1

혹시 Containing 을 안쓰신 이유가 있을까요?

0

89

2

[공유] 스프링부트 4.x 버전 mybatis 연동

0

184

1

@repository 어노테이션

0

94

3

ItemService

0

59

1

논리 커밋, 물리 커밋 질문드립니다.

0

54

1

내부 트랜잭션 커밋은 필수인가요?

0

57

1

프록시 커넥션 객체를 반환할 때 생성하는건가요?

0

55

1

Transaction readOnly 성능 개선 (김영한님의 대한 감사인사)

2

180

2

JPQL 대신 네이티브 쿼리를 사용해야 하는 경우

0

81

1

@EventListener(ApplicationReadyEvent.class) 관련

0

90

1

트랜잭션 동기화 매니저와 데이터 소스

0

77

1

DB 관련 강의 개설 계획은 없으신건가요?

0

134

2

물리 트랜잭션 과 논리트랜잭션 용어를 맞게 이해한걸까요

0

96

1

스프링 3 버전 이상 rollbackFor 변경된듯요

1

114

1

트랜잭션 전파 질문.

0

87

1

프로젝트 오픈 에러

0

126

1

외부 트랜잭션에서 isNewTransaction이 false로 나오는거에 대해 질문드립니다

0

84

2

같은 스레드를 사용하면 트랜잭션 동기화 매니저는 같은 커넥션을 반환

0

74

1

h2 인메모리 테스트중 예약어 충돌날 경우 대처방법

0

105

1