본문 바로가기

프로젝트/바이올렛 프로젝트

파일 올리기 + 썸네일

https://dololak.tistory.com/720

 

[서블릿/JSP] Apache Commons FileUpload를 이용한 파일업로드 구현하기

참고글 [HTTP] HTTP 환경에서 파일 업로드시 enctype multipart/form-data에 대한 설명 파일 업로드 웹 환경에서 파일업로드 는 많은곳에서 사용됩니다. 예를 들어 게시글의 첨부파일이나 회원가입시 프로

dololak.tistory.com

파일올리기에 대해서 설명을 잘해놓은거같다. 솔직히 졸려서 집중이 잘 안된다 ㅋㅋㅋㅋ

 

 

javascirpt로 이미지 경로를 mysql에 저장하려는데 에러가 난다.

insert에서 문제가 생겼다.

 

 

문제 에러 해결 방법
자바스크립트 .readAsDataURL() 앤 뭐지?? FileReader.readAsDataURL()
:컨텐츠를 특정 Blob 이나 File에서 읽어 오는 역할

https://developer.mozilla.org/ko/docs/Web/API/FileReader/readAsDataURL
java arguments [] https://hianna.tistory.com/522

mysql로 파일 경로가 따옴표로 묶여 있지 않아서
문자화 시켜주었다.

위 사이트를  보고 char quotes = '"'; 를 앞뒤로 붙여주었으나
차라리 String 받는게 낫다고 생각했다.
You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server 
version for the right syntax to use near
위 에러는 주로 따옴표를 안써서 그렇다고한다
https://ppost.tistory.com/entry/Mysqljdbc-%EC%BF%BC%EB%A6%AC%EB%AC%B8%EC%97%90%EC%84%9C-%EB%AC%B8%EB%B2%95%EC%97%90%EB%9F%AC%EA%B0%80-%EB%82%A0-%EA%B2%BD%EC%9A%B0%EA%B0%80-%EC%9E%88%EB%8B%A4
java arguments []

<div class="inputArea">
<label for="gdsImage">상품 이미지</label>
<input type="file" id="gdsImage" name="file" onchange="fileUpload(this);">
<div class="select_image">
<img alt="" src="">
</div>
<p>실제 경로 출력</p>
<%=request.getRealPath("/") %>
<%=request.getSession().getServletContext().getRealPath("/") %>
</div>

The error may involve defaultParameterMap parameterType="com.shopping.domain.GoodsVO"  추가
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax 처음에는 따옴표가 안들어가서 문자로 전달안됐나 해서
전달하는 값을 String으로 바꿔서 전달.

(`gdsName`, `cateCode`, `gdsPrice`, `gdsStock`, `gdsDesc`, 'gdsImage', 'gdsThumbImg') 오류 발생

(`gdsName`, `cateCode`, `gdsPrice`, `gdsStock`, `gdsDesc`, `gdsImage`, `gdsThumbImg`) 이렇게 바꿔주니까 됨 (해결!!)

` 과 ' 는 다르다

 

 

생각해보니까

이미지를 올리는 방법은

1) 경로

2) BlOB 이미지 https://kkh0977.tistory.com/988

라고 하는데 무슨 차이인지 아직은 모른다. 조사를 해봐야겠군. 

우선은 따라하고있는 사이트에서는 경로를 했으니... 경로로 한번 츄라이 츄라이!!

 

 

Java mysql 이미지 저장

 

 

블롭이 뭐지?

JavaScript에서 Blob(Binary Large Object, 블랍)은 이미지, 사운드, 비디오와 같은 멀티미디어 데이터를 다룰 때 사용

https://heropy.blog/2019/02/28/blob/

 

Blob(블랍) 이해하기

JavaScript에서 Blob(Binary Large Object, 블랍)은 이미지, 사운드, 비디오와 같은 멀티미디어 데이터를 다룰 때 사용할 수 있습니다. 대개 데이터의 크기(Byte) 및 MIME 타입을 알아내거나, 데이터를 송수신

heropy.blog

 

 

왜 이미지 불러올떄 절대경로가 적용이 안되지?

 

\D:\board\shopping\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\shopping\resources\imgUpload\2021\11\15\ac8d0ac8-0e36-45b5-b437-35600ab53b80_wonny.jpg 이걸로 하면 안됨
\resources\imgUpload\2021\11\15\ac8d0ac8-0e36-45b5-b437-35600ab53b80_wonny.jpg 이걸로 하면 됨

 

 

 

 

 

스프링에서 파일을 로컬에 저장하는 방법

참조: https://dev-gorany.tistory.com/123

 

# 1. Multipart의 transferTo(Path path) 이용하기

 @PostMapping(value = "/upload")
    public void uploadFile(MultipartFile[] uploadFiles){

        for(MultipartFile file : uploadFiles){

            String originalName = file.getOriginalFilename();
            String fileName = originalName.substring(originalName.lastIndexOf("\\") + 1);

            String uuid = UUID.randomUUID().toString();

            String savefileName = uploadPath + File.separator + uuid + "_" + fileName;

            Path savePath = Paths.get(savefileName);

            try {
                file.transferTo(savePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

 

 

 

# 2. FileCopyUtils의 copy() 이용하기

 @PostMapping(value = "/upload")
    public void uploadFile(MultipartFile[] uploadFiles){

        for(MultipartFile file : uploadFiles){

            String originalName = file.getOriginalFilename();
            String fileName = originalName.substring(originalName.lastIndexOf("\\") + 1);


            String uuid = UUID.randomUUID().toString();

            String savefileName = uploadPath + File.separator + uuid + "_" + fileName;

            Path savePath = Paths.get(savefileName);

            try {
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(savePath.toFile()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

실제 사용한 파일 저장 코드

 

 

파일을 생성하는 방법 3가지 https://hianna.tistory.com/588

이 사이트에서는

1. java.io.File

File file = new File("d:\\example\\file.txt"); // 파일 객체: 경로를 가리킬 뿐, 파일 생성 X

file.createNewFile(); // 파일 생성

 

2. java.io.FileOutputStream

File file= new File("d:\\example\\file.txt");// 파일 객체: 경로를 가리킬 뿐, 파일 생성 X

FileOutputStream fileOutputStream = new FileOutputStream(file, true); //파일 생성

3. java.nio.file.Files

Path filePath = Paths.get("d:\\example\\file.txt");

Path newFilePath = Files.createFile(filePath); // 파일 생성

 

4. FileCopyUtils.copy

File file= new File(ymdPath, newFileName);// 파일 객체: 경로를 가리킬 뿐, 파일 생성 X
FileCopyUtils.copy(fileData, file);//파일 저장 : 파일 바이트, 경로에 있는 새파일이름

 

5. Files.touch(file);

File tempDir = new File(System.getProperty("java.io.tmpdir"));

File file = new File(tempDir + "/text.txt");
System.out.println(file.toPath());
System.out.println(file.exists());

Files.touch(file);
System.out.println(file.exists());

Output:

/tmp/text.txt
false
true

출처: https://codechacha.com/ko/java-create-file-in-specific-dir/

 

 

 

 

파일의 절대경로

System.out.println("dir.getAbsolutePath() : " + dir.getAbsolutePath()); // 파일의 절대경로 ***

 

파일의 상대경로

System.out.println("dir.getPath() : " + dir.getPath()); // 파일의 상대경로 ***

출처: https://sas-study.tistory.com/90

 

 

'프로젝트 > 바이올렛 프로젝트' 카테고리의 다른 글

오류모음  (0) 2021.10.23
자바 + 쇼핑몰 만들기 오류 모음  (0) 2021.10.18
apache window 설치  (0) 2021.10.07