读取jsp网页上上传的文件是不能用request.getParameter(arg0);来读取的
因为request里面的键值对里的值只能存储String数组,不能存储文件
所以接下来就解决这个问题
布置网页
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'testFileUpload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="servlet/FileUploadTestServlet" method="post" enctype="multipart/form-data">
附件<input type="file" name="attachment"/>
<br/>
<input type="submit"/>
<br/>
</form>
</body>
</html>
写后台
public class FileUploadTestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//判断是否为enctype="multipart/form-data"
if(!ServletFileUpload.isMultipartContent(request)){
//如果不是,还是取属性方法不变
}else{
//创建上传所需的两个对象
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory); //解析器依赖于工厂
//从request的流中解析出表单每个属性的 名值对(FileItem)。注意:这个值可能是字符串,也可能是文件
List<FileItem> items = sfu.parseRequest(request);
for(FileItem item:items){
String name = item.getFieldName();//表单的name属性的名字(名值对里的名)
// InputStream valueStream = item.getInputStream();//(名值对里的值)这个是值对象,因为值可以是字符串也可以是文件,所以我们用字节流的方式来获取数据
//isFormField()方法是判断当前表单项是不是字符串类型的值
if(item.isFormField()){
String value = item.getString("utf-8");//获取当前表单项的字符串
}else{
String fileName = item.getName();//获取文件名
String contentType = item.getContentType();//获取http请求中该文件的mime类型
File f = new File("e:/aaa/");
if(!f.exists())
f.mkdir();
item.write(new File("e:/aaa/bbb.jpg"));
//item.write(new File("e:/aaa/aaa.docx"));
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
需要导入两个包
注意: