티스토리 뷰

자바(Java)

자바 파일 업로드 소스

xemaker 2018. 11. 15. 14:14

자바 파일 업로드 방법은 여러가지가 있을 수 있는데 그 중 한가지 방법을 공유한다.


FileInputStream fileInputStream = new FileInputStream(filePath);


String lineEnd="\r\n";

String twoHyphens="--";

String boundary="******";


String url="/interface/uploadAttachFile.do";

HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();

con.setRequestMethod("POST");


con.setDoOutput(true);

con.setDoInput(true);

con.setUseCaches(false);

con.setRequestProperty("Connection","Keep-Alive");

con.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);


DataOutputStream dos=new DataOutputStream(con.getOutputStream());


dos.writeBytes(twoHyphens+boundary+lineEnd);

String strSend=String.format("Content-Dispostition: form-data; name=\"upload_file\"; filename=\%s\"\r\n", fileNm);

dos.writeBytes(strSend);

dos.writeBytes(lineEnd);


int bytesAvailable=fileInputStream.available();

int maxBufferSize=1024;

int bufferSize=Math.min(bytesAvailable, maxBufferSize);

byte[] buffer=new byte[bufferSize];

int bytesRead=fileInputStream.read(buffer,0,bufferSize);


while(bytesRead>0){

dos.write(buffer,0,buferSize);

bytesAvailable=fileInputStream.available();

bufferSize=Math.min(bytesAvailable, maxBufferSize);

bytesRead=fileInputStream.read(buffer,0,bufferSize);

}

dos.writeBytes(lineEnd);

dos.wirteBytes(twoHyphens+boundary+twoHyphens+lineEnd);


fileInputStream.close();

dos.flush();


BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));

for(String line=null;(line=br.readLine())!=null;){

result.append(line);

}


if(result.length()!=0){

logger.info("결과="+result.toString());

}

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
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
글 보관함