做系统,有时会需要实现文件上传的功能,在这里我用servlet来实现文件的http://上传,为了开发方便,我们需要下载两个文件:commons-fileupload.jar;commons-io-2.3前一个需要依赖后一个,所以两个都要下载,配置好后就可以编写代码了。
首先编写jsp文件:
<%@ 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 'index.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="UploadServlet" method="post" enctype="multipart/form-data">
username:<input type="text" name="username"/><br/>
file: <input type="file" name="file" /><br/>
file: <input type="file" name="file2"/><br/>
<input type="submit" value="ok"/>
</form>
</body>
</html>
这里需要说明的是:form表单一点要有enctype属性并且其值为:multipart/form-data。
然后是编写servlet了,很简单:
package com.nine.upload.action;
import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
String path = request.getRealPath("/upload");
factory.setRepository(new File(path));
factory.setSizeThreshold(1024 * 1024);
ServletFileUpload upload = new ServletFileUpload(factory);
//设置上传文件大小
upload.setSizeMax(2 * 1024 * 1024);
try {
List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
for (FileItem item : list) {
String name = item.getFieldName();
if (item.isFormField()) {
//文本域
String value = item.getString();
System.out.println("name ----> " + name);
System.out.println("value ----> " + value);
request.setAttribute(name, value);
} else {
//文件本身
String value = item.getName();
System.out.println("value ----> " + value);
int start = value.lastIndexOf("\\");
String fileName = value.substring(start + 1);
request.setAttribute(name, value);
item.write(new File(path, fileName));
}
}
} catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("uploadresult.jsp").forward(request, response);
}
}
就这样了,文件上传就实现了