본문 바로가기
Tech/Web

[Servlet] File upload

by 소라소라잉 2019. 10. 24.

<원시적인 방법>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package org.zerock.controller;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
 
@WebServlet("/upload")
@MultipartConfig(maxFileSize = 1024 * 1024 * 10, maxRequestSize = 1024 * 1024 * 50, fileSizeThreshold = 1024
        * 1024, location = "C://zzz")
// location 임시보관소.(not저장장소 1MB가 넘어가면 zzz에 잠깐 보관할 수 있다)
public class UploadController extends HttpServlet {
    // maxRequestSize : 여러개의 파일을 업로드할때 총 size
 
    private static final long serialVersionUID = 1L;
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Collection<Part> parts = request.getParts();
        parts.forEach(part -> {
 
            System.out.println(part.getContentType() + "" + part.getSize() + part.getSubmittedFileName());
 
            byte[] buffer = new byte[1024 * 8];
 
            try {
                InputStream in = part.getInputStream();
                FileOutputStream fos = new FileOutputStream("C:\\zzz\\upload\\" + part.getSubmittedFileName());
 
                while (true) {
                    int count = in.read(buffer);
                    if (count == -1)
                        break;
                    fos.write(buffer, 0, count);
                }
 
                in.close();
                fos.close();
 
            } catch (Exception e) {
                e.printStackTrace();
            }
 
        });
    }
 
}
 
cs

 

 

파일 이름 중복 문제 해결법(with token)

1) currentTime

2) UUID (파일 이름에 Unique한 값을 부여)

 

<Commons IO library를 이용하는 방법> 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package org.zerock.controller;
 
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
 
import org.apache.commons.io.FileUtils;
 
@WebServlet("/upload")
@MultipartConfig(maxFileSize = 1024 * 1024 * 10, maxRequestSize = 1024 * 1024 * 50, fileSizeThreshold = 1024
        * 1024, location = "C://zzz")
// location 임시보관소.(not저장장소 / 1MB가 넘어가면 zzz에 잠깐 보관할 수 있다)
public class UploadController extends HttpServlet {
    // maxRequestSize : 여러개의 파일을 업로드할때 총 size
 
    private static final long serialVersionUID = 1L;
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Collection<Part> parts = request.getParts();
        parts.forEach(part -> {
 
            System.out.println(part.getContentType() + "" + part.getSize() + part.getSubmittedFileName());
 
            try {
                InputStream in = part.getInputStream(); // 업로드되는 파일로부터 데이터를 뽑아내야 하니 필요함 
                File file = new File("C:\\zzz\\upload\\" + System.currentTimeMillis()+"_"+part.getSubmittedFileName());
                // 파일이름 중복문제 해결 -> 파일명 앞에 currentTimeMilles를 붙여준다.
                FileUtils.copyInputStreamToFile(in, file);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
 
        });
    }
 
}
 
cs

 

 

 

 

댓글