JSP 는 Common FileUpload 구성 요 소 를 사용 하여 파일 업로드 및 업로드 형식 인 스 턴 스 코드 제한
3712 단어 jspCommonFileUpload파일 업로드
<body>
<h2> </h2>
<form action="LimitFile" name="one" enctype="multipart/form-data" method="post">
rar :
<input type="file" name="fileupload" value="upload" />
<input type="submit" value=" "> <input type="reset" value=" ">
</form>
</body> 상기 코드 지정 제출 후 요청 을 LimitFile 처리 에 제출 합 니 다.LimitFile(Servlet)은 업로드 파일 을 처리 하고 파일 형식 이 일치 하 는 지 판단 하여 업로드 결 과 를 표시 합 니 다.2.LimitFile 이라는 Servlet 를 만 들 고 doPost()방법 에서 구현 코드 를 작성 합 니 다.다음 과 같 습 니 다.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String uploadpath = "";
DiskFileItemFactory factory = new DiskFileItemFactory();
// , 。
factory.setSizeThreshold(30 * 1024);
// setSizeThreshold() , 。
factory.setRepository(factory.getRepository());
ServletFileUpload upload = new ServletFileUpload(factory);
List list = null;
try{
list = upload.parseRequest(request);
String[] limit = new String[]{".jpg", ".gif", ".png", ".bmp"};
//
SuffixFileFilter filter = new SuffixFileFilter(limit);
// SuffixFileFilter
Iterator iterator = list.iterator();
while(iterator.hasNext()){
FileItem item =(FileItem)iterator.next();
if(!item.isFormField()){
String filePath = item.getName();
if(filePath != null){
File filename= new File(filePath);
File uploadFile = new File(request.getSession().getServletContext().getRealPath("/") + "upload");
uploadpath = uploadFile.getAbsolutePath()+File.pathSeparator + uploadpath;
// ";" ,
uploadpath = uploadpath.substring(0, uploadpath.length()-1);
File saveFile = new File(uploadpath,filename.getName());
boolean flag = filter.accept(saveFile);
if(flag){
out.print(" ");
break;
}else{
try {
item.write(saveFile);
out.print(" ");
} catch (Exception e) {
out.print(" ");
e.printStackTrace();
}
}
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
}
}이 코드 는 바이트 문자열 배열 limit 에서 업로드 할 수 없 는 파일 형식 을 정의 한 다음 이 배열 을 Suffix FileFilter 류 에 전달 하 는 구조 함수 입 니 다.이 종류의 accept()방법 을 통 해 현재 업로드 한 파일 이 조건 에 부합 되 는 지 검증 합 니 다.마지막 으로 파일 을 항목 의 upload 디 렉 터 리 에 저장 합 니 다.총결산
위 에서 말 한 것 은 소 편 이 소개 한 JSP 가 Common FileUpload 구성 요 소 를 사용 하여 파일 업로드 및 업로드 형식 인 스 턴 스 코드 를 제한 하 는 것 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 저 에 게 메 시 지 를 남 겨 주세요.소 편 은 제때에 답 해 드 리 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JSP| EL (Experession Language)텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.