准备工作,引入jar包:
commons-fileupload-1.2.1.jar
commons-io-1.4
java页:
package com.baidu.com;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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 com.sun.xml.internal.bind.v2.runtime.Name;
public class Test4 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//先建立磁盘文件项工厂
DiskFileItemFactory diskFileItemFactory =new DiskFileItemFactory();
//创建一个核心解析类
ServletFileUpload fileupload = new ServletFileUpload(diskFileItemFactory);
//利用核心解析类解析Request
List<FileItem> list = fileupload.parseRequest(request);
//遍历这个List集合,得到代表每个部分的文件项对象,根据判断是否是文件
for (FileItem fileItem : list) {
//判断这个问津是普通箱还是文件上传项
if (fileItem.isFormField()) {
//普通箱
//接受普通项目的值
//如果是普通箱那就取普通项的名称和值(接受值不能再使用request.getparameter())
String name = fileItem.getFieldName();
//拿普通类型的值
String value = fileItem.getString("UTF-8");
System.out.println("输出打印 :"+ name +" "+value);
//
}else {
//文件上传项
//获得文件上传的文件名称
String filename = fileItem.getName();
//获得文件上传的文件数据
InputStream is = fileItem.getInputStream();
//获得文件上传的文件的路径 ,池畔的绝对路径
String realpath = getServletContext().getRealPath("./a");
//创建一个输出流写入到刚才(上面)的设置的路径中
OutputStream os = new FileOutputStream(realpath+"/"+filename);
//以下两个输出流,利用之前所学的数组传输字节流对象
//定义一个int类型的变量
int len = 0;
//定义一个byte类型的数组
byte[] b = new byte[1024];
while ((len = is.read(b))!= -1) {
os.write(b, 0, len);
}
os.close();
is.close();
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
.jsp页:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTf-8">
<title>Insert title here</title>
</head>
<body>
<h1>文件上传</h1>
<form action="/shangchuanxiazai/Test1" method="post" enctype="multipart/form-data">
文件描述:<input type ="text" name="info"><br>
文件上传:<input type="file" name = "up"><br>
<input type = "submit" value="上传">
</form>
</body>
</html>