【javaweb】form表单的文件上传demo
程序员文章站
2022-04-29 17:37:48
...
1.基础知识
2.demo如下
package indi.fileupload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
public class Fileuploadservlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.第一步新建一个磁盘文件项工厂
String path_temp=this.getServletContext().getRealPath("temp");
//第一个参数是设置缓存文件的大小(也就是要多大才缓存),第二个参数是设置缓存的地址
//DiskFileItemFactory factory=new DiskFileItemFactory(1024*1024, new File(path_temp));
//当然也可以这样设置
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024);//设置缓存大小为1M
factory.setRepository(new File(path_temp));
//2.第二步新建一个文件上传的核心类
ServletFileUpload upload=new ServletFileUpload(factory);
//3.判断是否是一个文件上传的表单,即判断是否是enctype="multipart/form-data"
boolean multipartContent = ServletFileUpload.isMultipartContent(request);
if(multipartContent) {
//是文件上传类表单
//4.设置上传文件名的编码方式,目的是解决文件名为中文的乱码问题
upload.setHeaderEncoding("UTF-8");
//5.解析request获得表单项的集合,设置设置泛型为FileItem
List<FileItem> parseRequest=null;
try {
parseRequest = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
//6.遍历文件项集合
for(FileItem item:parseRequest) {
//7.判断是否是普通表单项
boolean formField = item.isFormField();
if(formField) {
//普通表单项
//获得表单的name属性值
String fieldName=item.getFieldName();
String fieldValue=item.getString("UTF-8");//参数表示对普通表单项的内容进行UTF-8编码,防止中文乱码,若非中文直接getString()
System.out.println(fieldName+"----"+fieldValue);
}else {
//文件上传项
//获得文件上传的内容
String fileName=item.getName();
//获得上传文件的输入流
InputStream in = item.getInputStream();
//将输入流的数据copy至服务器上
String path_store=this.getServletContext().getRealPath("upload");
//新建一个输出流
FileOutputStream out = new FileOutputStream(new File(path_store+"/"+fileName));//当然也可以直接path_store+"/"+fileName
int len=0;
byte[] buffer = new byte[1024];
while((len=in.read(buffer))>0) {
out.write(buffer, 0, len);
}
//当然上面的操作可以通过IO工具简化书写,其它步骤相同
//IOUtils.copy(in, out);
in.close();
out.close();
//8.删除临时文件
item.delete();
}
}
}else {
//是传统表单
//那么就用传统的request.getAttribute(arg0)就行
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
上一篇: bootstrap-table + 事件 + 动态生成模态框
下一篇: 表格标签table的使用