파일 업로드 구성 요 소 를 사용 하여 파일 업로드 기능 을 실현 합 니 다.
6978 단어 fileupload파일 업로드
fileUpload 는 apache 의 comons 구성 요소 가 제공 하 는 업로드 구성 요소 입 니 다.가장 중요 한 작업 은 request.getInpustream()을 분석 하 는 것 입 니 다.
fileUpload 구성 요 소 를 사용 하려 면 먼저 두 개의 jar 패 키 지 를 도입 해 야 합 니 다.
fileUpload 고정 절차 사용:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="uploadServlet" enctype="multipart/form-data" method="post">
<input type="text" name="username">
<input type="password" name="pwd">
<input type="file" name="pic">
<input type="submit">
</form>
</body>
</html>
UploadServlet
package pers.zhang.servlet;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
request.setCharacterEncoding("utf-8");
//
// upload.setHeaderEncoding("utf-8");
//
factory.setSizeThreshold(1024*1024*10);
File uploadTemp=new File("e:\\uploadTemp");
uploadTemp.mkdirs();
factory.setRepository(uploadTemp);
//
upload.setFileSizeMax(1024*1024*10);
//
upload.setSizeMax(1024*1024*30);
try {
List<FileItem> list=upload.parseRequest(request);
System.out.println(list);
for (FileItem fileItem:list){
if (!fileItem.isFormField()&&fileItem.getName()!=null&&!"".equals(fileItem.getName())){
String filName=fileItem.getName();
// UUID ,
String uuid= UUID.randomUUID().toString();
//
String suffix=filName.substring(filName.lastIndexOf("."));
// , upload 。 , WEB-INF
String uploadPath=request.getSession().getServletContext().getRealPath("/upload");
File file=new File(uploadPath);
file.mkdirs();
// , , ,
fileItem.write(new File(uploadPath,uuid+suffix));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
테스트콘 솔 인쇄:
[name=null, StoreLocation=e:\uploadTemp\upload_9e72474_16ddcccabe6__8000_00000000.tmp, size=5bytes, isFormField=true, FieldName=username, name=null, StoreLocation=e:\uploadTemp\upload_9e72474_16ddcccabe6__8000_00000001.tmp, size=6bytes, isFormField=true, FieldName=pwd, name=C:\Users\19798\Desktop\test.txt, StoreLocation=e:\uploadTemp\upload_9e72474_16ddcccabe6__8000_00000002.tmp, size=20bytes, isFormField=false, FieldName=pic]
프로젝트 배치 경로 에서 upload 폴 더:fileUpload 구성 요 소 를 사용 하여 파일 업 로드 를 실현 합 니 다.위의 방법 외 에 도 주의해 야 할 것 은:
Apache 파일 업로드 구성 요 소 는 업 로드 된 데이터 의 각 필드 내용 을 분석 할 때 뒤에 데 이 터 를 추가 처리 할 수 있 도록 해 석 된 데 이 터 를 임시로 저장 해 야 합 니 다(디스크 의 특정 위치 에 저장 하거나 데이터 베 이 스 를 삽입).자바 가상 컴퓨터 가 기본적으로 사용 할 수 있 는 메모리 공간 이 제한 되 어 있 기 때문에 제한 을 초과 하면'자바.lang.OutOfmory Error'오류 가 발생 합 니 다.만약 에 업로드 한 파일 이 매우 크다 면,예 를 들 어 800 M 의 파일 은 메모리 에 이 파일 의 내용 을 임시로 저장 할 수 없고,아파 치 파일 업로드 구성 요 소 는 임시 파일 로 이 데 이 터 를 저장한다.그러나 업로드 한 파일 이 매우 작다 면,예 를 들 어 600 바이트 의 파일 은 메모리 에 직접 저장 하 는 것 이 더욱 좋 을 것 이다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
java는common-fileupload를 사용하여 파일 업로드를 실현합니다파일 업로드는 사이트에서 매우 자주 사용하는 기능으로 Servlet을 직접 사용하여 업로드 파일을 가져오려면 요청 파라미터를 해석해야 하기 때문에 비교적 번거롭기 때문에apache의 소스 오픈 도구,common-fi...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.