需要 commons-io与commons-fileupload
首先在jsp中创建一下布局
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="MyServlet" method="post" enctype="multipart/form-data">
最简单的文件上传:<input type="file" name="fileupload"/>
描述:<input type="text" name="desc"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
然后创建一个servlet类
并在dopost方法中写入上传文件代码
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
//1、创建一个DiskFileItemFactory工厂
DiskFileItemFactory factory =newDiskFileItemFactory();
//2、创建一个文件上传解析器
ServletFileUpload upload =newServletFileUpload(factory);
//解决上传文件名的中文乱码
upload.setHeaderEncoding("UTF-8");
factory.setSizeThreshold(1024*500);//设置内存的临界值为500K
File linshi =newFile("E:\\linshi");//当超过500K的时候,存到一个临时文件夹中
factory.setRepository(linshi);
upload.setSizeMax(1024*1024*5);//设置上传的文件总的大小不能超过5M
try{
// 1. 得到 FileItem 的集合 items
List<FileItem>/* FileItem */items = upload.parseRequest(request);
// 2. 遍历 items:
for(FileItem item : items){
// 若是一个一般的表单域, 打印信息
if(item.isFormField()){
String name = item.getFieldName();
String value = item.getString("utf-8");
System.out.println(name +": "+ value);
}
// 若是文件域则把文件保存到 e:\\files 目录下.
else{
String fileName = item.getName();
long sizeInBytes = item.getSize();
System.out.println(fileName);
System.out.println(sizeInBytes);
InputStream in = item.getInputStream();
byte[] buffer =newbyte[1024];
int len =0;
fileName ="e:\\files\\"+ fileName;//文件最终上传的位置
System.out.println(fileName);
OutputStream out =newFileOutputStream(fileName);
while((len = in.read(buffer))!=-1){
out.write(buffer,0, len);
}
out.close();
in.close();
}
}
}catch(FileUploadException e){
e.printStackTrace();
}
时间: 2024-12-27 15:25:42