J2EE学习笔记——文件的上传
文件上传需要 两个JAR包:commons-httpclient-3.1.jar
org.apache.commons-fileupload-1.2.1.jar
index.jsp:
[html]
<body>
上传文件 <br>
<form action="UpLoadServer" method="post" enctype="multipart/form-data" >
用户名: <input type="text" name="username" ><br>
文件: <input type="file" name="file" >
<input type="submit" value="上传">
</form>
</body>
</html>
==============================================================================
servlet代码:
[java]
package xuyan.com;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
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.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UpLoadServer extends HttpServlet {
private String[] fileExts={"doc","zip","rar","jpg","txt"};
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//检查请求是否是一个上传表单(必须是post请求,和enctype=“multipart/form-date”)
Boolean isMultipart=ServletFileUpload.isMultipartContent(request);
if(isMultipart)
{
//创建一个临时文件存放要上传的文件,第一个参数是上传文件大小,第二个参数是存放的临时目录
DiskFileItemFactory factory=new DiskFileItemFactory(1024*1024*5,new File("D:\\temp"));
//创建一个文件上传的句柄
ServletFileUpload upload=new ServletFileUpload(factory);
//设置文件上传的整个大小和上传的单个文件大小
upload.setSizeMax(1024*1024*50);
upload.setFileSizeMax(1024*1024*5);
try {
//把页面表单中每一个表单元解析成一个Fileitem
List<FileItem> items=upload.parseRequest(request);
for(FileItem fileItem:items)
{
//如果是一个普通的表单元素(type不是files的表单元素)
if(fileItem.isFormField())
{
//System.out.println(fileItem.getFieldName()); //得到对应表单元素的名字
System.out.println(fileItem.getString());//得到表单元素的值
}
else
{
//获取文件的后缀名
String filename=fileItem.getName();//得到文件名
String fileExt=filename.substring(filename.lastIndexOf(".")+1, filename.length());
if(Arrays.binarySearch(fileExts, fileExt)!=-1)
{
try {
//将文件上传到u
补充:综合编程 , 其他综合 ,