file업로드시에는 getParameter로는 안됩니다.


[ 다음 글들 ] [ 이어서 글올리기(답하기) ] [ 자바 묻고 답하기 ]

글쓴이 :임채환 1999년 4월 22일 11:45:54

In Reply to: [질문]서블릿에서 파일과 파라미터를 같이 받으려면... posted by 남 재범 on 1999년 4월 03일 18:56:12:

파일업로드는 FORM문에서 ENCTYPE을 "multipart/form-data"로 합니다.
그런데 파일이외의 즉, 이름, 제목, 내용 등등의 값을 받고자 할때는 getParameter()로는 안됩니다.
filename추출하는 것을 응용해서 받으셔야 합니다.


다음은 파일업로드기능만 있는 김덕태님의 소스를 약간수정한 것입니다.


여기에서는 파일 등록자와 파일만 받는 것으로 했습니다.


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class FileUploadServlet extends HttpServlet
{
public void doGet( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
res.setContentType("text/html; charset=euc-kr");


PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream()));
out.println("<p>"+req.getServletPath()+"</p>");
out.println("<FORM ACTION=\""+req.getServletPath()+"\" METHOD=POST
ENCTYPE=\"multipart/form-data\">");
out.println("What is your name? <INPUT TYPE=TEXT NAME=sender > <BR>");
out.println(" Which file to upload? <INPUT TYPE=FILE NAME=file_upload> <BR>");
out.println("<INPUT TYPE=SUBMIT> </FORM>");
out.flush();
out.close();
}


public void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
ServletInputStream fromClient = req.getInputStream();
res.setContentType("text/html; charset=euc-kr");
PrintWriter toClient=new PrintWriter(new OutputStreamWriter(res.getOutputStream(),"KSC5601"));


String name;
String filename = null;
String contentType = null;
File file=null;
FileOutputStream toFile = null;


try
{
int ind = req.getContentType().indexOf("boundary=");
if (ind == -1)
throw new IOException();
String boundary = req.getContentType().substring(ind+9);
if (boundary == null)
throw new IOException();


String endBoundary = "--" + boundary + "--";


String line;
String lowerLine;
byte[] lineBuf = new byte[1024*8];
int lineLen;


// -------- name 인자와 값 추출
// 바운더리 표식 제거
fromClient.readLine(lineBuf, 0, lineBuf.length);


// Content-Disposition 헤더 처리
lineLen = fromClient.readLine(lineBuf, 0, lineBuf.length);
line = new String(lineBuf, 0, lineLen);
lowerLine = line.toLowerCase();
ind = lowerLine.indexOf("content-disposition:") + 20;
ind = lowerLine.indexOf("form-data;", ind) + 10;
int nameStart = lowerLine.indexOf("name=\"", ind) + 6;
int nameEnd = lowerLine.indexOf("\"", nameStart);
if ( nameStart == -1 || nameEnd == -1 )
throw new IOException();
name = line.substring(nameStart, nameEnd);


// 공백라인 제거
fromClient.readLine(lineBuf, 0, lineBuf.length);


// 실제 값 읽기
lineLen = fromClient.readLine(lineBuf, 0, lineBuf.length); // 라인의 길이
line = new String(lineBuf, 0, lineLen); // 스트링으로 읽기
lowerLine = line.toLowerCase();
String name_value=lowerLine.trim();
//--------------- name 추출 End


//------------------file name과 내용 추출
// 바운더리 표식 제거
fromClient.readLine(lineBuf, 0, lineBuf.length);


// Content-Disposition 헤더 처리
lineLen = fromClient.readLine(lineBuf, 0, lineBuf.length);
line = new String(lineBuf, 0, lineLen);
lowerLine = line.toLowerCase();
ind = lowerLine.indexOf("content-disposition:") + 20;
ind = lowerLine.indexOf("form-data;", ind) + 10;
nameStart = lowerLine.indexOf("name=\"", ind) + 6;
nameEnd = lowerLine.indexOf("\"", nameStart);
if ( nameStart == -1 || nameEnd == -1 )
throw new IOException();
String file_upload = line.substring(nameStart, nameEnd);


int filenameStart = lowerLine.indexOf("filename=\"", ind) + 10;
int filenameEnd = lowerLine.indexOf("\"", filenameStart);
if ( filenameStart != -1 && filenameEnd != -1 )
filename = line.substring(filenameStart, filenameEnd);


// Content-Type 헤더가 있으면 처리한 후, 블랭크 라인을 읽어들인다.
lineLen = fromClient.readLine(lineBuf, 0, lineBuf.length);
line = new String(lineBuf, 0, lineLen);
lowerLine = line.toLowerCase();
if (lowerLine.startsWith("content-type:"))
{
contentType = line.substring(13).trim();
lineLen = fromClient.readLine(lineBuf, 0, lineBuf.length);
line = new String(lineBuf, 0, lineLen);
}


if ( ! line.equals("\r\n") )
throw new IOException();


// 데이타를 읽어들여서 화일에 저장한다.
int start = filename.lastIndexOf('\\');
// file = new File("/databank",filename.substring(start+1));
// toClient.println("file : "+filename.substring(start+1));
toFile = new FileOutputStream("c:\\temp\\"+filename.substring(start+1));
byte[] lineBuf2 = new byte[1024*8];
int lineLen2 = 0;
lineLen = fromClient.readLine(lineBuf, 0, lineBuf.length);
if (lineLen == -1)
throw new IOException();


line = new String(lineBuf2, 0, lineLen2, "iso-8859-1");
while (! line.startsWith(endBoundary))
{
toFile.write(lineBuf2, 0, lineLen2);
System.arraycopy(lineBuf, 0, lineBuf2, 0, lineLen);
lineLen2 = lineLen;
lineLen = fromClient.readLine(lineBuf, 0, lineBuf.length);
if (lineLen == -1)
throw new IOException();
line = new String(lineBuf, 0, lineLen, "iso-8859-1");
}
if ( lineLen2 >= 2)
toFile.write(lineBuf2, 0, lineLen2-2);
toFile.close();
//---------------- filename과 내용 추출


// 웹 문서 생성
toClient.println("<html><head><title>화일 업로드 결과"
+ "</title></head>");
toClient.println("<body>다음 화일이 업로드되었습니다.");
toClient.println("<br><b>name: " + name + "<br>");
toClient.println("<br><b>name_value: " + name_value + "<br>");
toClient.println("<br><b>file: " + file_upload + "<br>");
toClient.println("<b>filename: " + filename + "<br>");
toClient.println("Content-Type: " + contentType + "<br>");
toClient.println("</body></html>");
} catch( IOException e )
{
toClient.println("<html><head><title>화일 업로드 오류"
+ "</title></head><body>");
toClient.println("문제가 발생하였습니다.");
toClient.println("다시 업로드하시기 바랍니다.");
toClient.println("</body></html>");
e.printStackTrace();
} finally
{
toClient.flush();
toFile.close();
toClient.close();
}
}
}


다음 글들:



이어서 글올리기(답하기)

이름:
E-Mail:
제목:
내용:
HTML 태그 포함 여부: HTML 문서일 경우 체크
관련 URL(선택):
URL 제목(선택):
관련 이미지 URL:


[ 다음 글들 ] [ 이어서 글올리기(답하기) ] [ 자바 묻고 답하기 ]