전자정부표준프레임워크
api 파일 전송
yeon.Biju
2022. 4. 14. 11:27
카카오 친구톡에 이미지를 전송하는 부분이 있어서 api를 통해 파일전송을 해야 하는데 어떻게 하는지 몰라서 한참을 찾아헤맸다.
작업한 내용을 정리해본다.
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
URL url;
HttpURLConnection conn;
final String boundary = "*****";
final String CRLF = "\r\n";
OutputStream os =null;
DataOutputStream dos =null;
FileInputStream fis = null;
InputStream dis =null;
ByteArrayOutputStream baos = null;
int responseCode = 0;
String resStr = "";
requestUrl ="https://.........";
try {
url = new URL(requestUrl);
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(3000); //3초
conn.setReadTimeout(3000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
//file
File file = new File("파일의 물리적 경로");
os =conn.getOutputStream();
dos = new DataOutputStream(os);
String filename =new String("파일명".getBytes("UTF-8"),"ISO-8859-1"); //파일명 한글처리
dos.writeBytes("--" + boundary + CRLF);
dos.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\""+filename+"\"" + CRLF);
dos.writeBytes(CRLF);
fis = new FileInputStream(file);
int buffersize;
while( (buffersize = Math.min(fis.available(),1024)) > 0) {
byte[] buffer = new byte[buffersize];
fis.read(buffer,0,buffersize);
dos.write(buffer);
}
dos.writeBytes(CRLF);
dos.writeBytes("--"+boundary+"--"+CRLF);
fis.close();
dos.flush();
dos.close();
os.close();
responseCode = conn.getResponseCode(); //요청
if(responseCode==200){
dis = conn.getInputStream();
byte[] bytes = new byte[1024];
baos = new ByteArrayOutputStream();
while(bytes.length > 0){
int red = dis.read(bytes,0,bytes.length);
if(red<0)
break;
baos.write(bytes,0,red);
}
resStr =(baos.toString("UTF-8"));
}
if(baos !=null) {
baos.flush();
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
if (dos != null) try { dos.close(); } catch (IOException ignore) {}
if (fis != null) try { fis.close(); } catch (IOException ignore) {}
if (dis != null) try { dis.close(); } catch (IOException ignore) {}
if (baos != null) try { baos.close(); } catch (IOException ignore) {}
}
|
cs |
처음하는 거니 좀 헤메게 되었는데...
인터넷에 위의 소스는 쉽게 구할 수 있는데도 말이다.
그게 아래와 같은 소스 때문인데.. 이런 부분들이 왜 들어가는지는 잘 모르겠다.
처음에 안넣고 하니 오류가 나와서 뭐가 문제인지 파악을 못해서 금방 끝날 작업을 생각보다 많은 시간을 허비했다.
dos.writeBytes("--" + boundary + CRLF);
이 부분 말고도 --, CRLF, boundary 이 3가지를 잘 써야했었다.