文件上传至服务器

2021-07-05 21:03

阅读:457

标签:0kb   web   bsp   block   string   用户   路径   port   private   

使用文件上传至服务器需要导入两包commons-fileupload-1.2.2.jar与commons-io-2.4.jar

本文的servlet使用的是 servlet3.0注解配置,   不用写web.xml 文件了

建立文件时使用javaEE6.0 支持servlet3.0

value的值就是访问路径
urlPatterns的值也是访问路径  例如
@WebServlet(name="DemoServlet3",value="/demoServlet3")
public class DemoServlet3 extends HttpServlet {
...
}

文件上传的表单

method 必须是post
enctype="multipart/form-data"

例如


用户名:
请选择文件:

  

创建表单的步骤

1.创建DiskFileItemFactory 工厂
DiskFileItemFactory dif = new DiskFileItemFactory();
2.创建ServletFileUpload 对象
ServletFileUpload sfu = new ServletFileUpload(dif);
3.判断表单提交 是不是 multipart/form-data
boolean isMultipart = sfu.isMultipartContent(request);

整体代码如下:

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;


@WebServlet(name="UploadServlet" ,urlPatterns="/uploadServlet")
public class UploadServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("------------文件上传----------------");
		//文件上传路径   我的文件上传的是F:\tomcat7\webapps\javaweb下的新建file文件夹里
		String readPath=this.getServletContext().getRealPath("file");
		//创建DiskFileItemFactory工厂
		DiskFileItemFactory dif=new DiskFileItemFactory();
		ServletFileUpload sfu=new ServletFileUpload(dif);
		boolean iMmultipart = sfu.isMultipartContent(request);
		if(iMmultipart){
			//进行文件上传
			try {
				//解析请求    获取表单元素即表单的全部提交信息
				List items =sfu.parseRequest(request);
				if(items!=null){
					for (FileItem item : items) {
						if(item.isFormField()){          //判断是否是普通字段(即上传的用户名密码等)
							String fileName=item.getFieldName();
							String value=item.getString("UTF-8");
							System.out.println(fileName+"----------"+value);     //读取用户名密码等文件
							
						}else{
							//是要上传的文件
							//获取上传的文件名
							String fileName=item.getName();
							System.out.println("上传的文件名: "+fileName);
						          	//新建一个文件对象 第一个参数放文件上产路径
							File file=new File(readPath,fileName);
							//开始上传
							item.write(file);
							System.out.println("文件上传成功! 文件名是"+fileName);
						}
					}
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			doGet(request, response);
	}

  

如果再加上
限制文件上传的类型和大小
类型:
List filTypes = Arrays.asList("jpg","png","gif","bmp");

大小:
//设置单个文件的最大限制
upload.setSizeMax(1024*30); 

获取上传文件名的后缀:
String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
System.out.println("后缀:"+fileType);
boolean flag = filTypes.contains(fileType);

完整的代码如下:

package cn.bdqn.demo;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet(name="UploadServlet",value="/uploadServlet")
public class UploadServlet extends HttpServlet {
	
	private static final long serialVersionUID = -2590255173244980573L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("----文件上传---------");
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		//获取上传文件的路径
		String realPath = this.getServletContext().getRealPath("files");
		System.out.println("上传路径:"+realPath);
		//1.创建DiskFileItemFactory
		DiskFileItemFactory dif = new DiskFileItemFactory();
		//2.创建ServletFileUpload 对象
		ServletFileUpload sfu = new ServletFileUpload(dif);
		//3.判断表单提交 是不是 multipart/form-data
		boolean isMultipart = sfu.isMultipartContent(request);
		if(isMultipart){
			//进行文件上传
			//ServletFileUpload 解析请求 获取元素集合
			List filTypes = Arrays.asList("jpg","png","gif","bmp");
			//限定单个文件的大小
			sfu.setSizeMax(1024*30);    //最大30KB
			try {
				List items = sfu.parseRequest(request);
				if(items!=null){
					for(FileItem item : items){
						if(item.isFormField()){   //判断是否是普通字段
							String fieldName = item.getFieldName();
							String value = item.getString("UTF-8");
							System.out.println(fieldName+"---"+value);
						}else{
							//是文件   文件上传
							//获取上传的文件名
							String fileName = item.getName();
							//判断文件类型是否匹配:
							//获取后缀
							String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
							System.out.println("后缀:"+fileType);
							boolean flag = filTypes.contains(fileType);
							if(flag){
								System.out.println("上传的文件名:"+fileName);
								//新建一个文件对象   第一个参数放文件上传路径
								File file = new File(realPath, fileName);
								//开始上传
								item.write(file);
								System.out.println("文件上传成功!");
								response.getWriter().print("文件上传成功!");
							}else{
								response.getWriter().print("上传失败!文件类型必须是jpg,png,gif,bmp!");
							}
						}
					}
				}
			}catch (FileUploadBase.SizeLimitExceededException e) {
				System.out.println("上传失败,文件太大,单个文件的最大限制是:"+sfu.getSizeMax()+"bytes!");
				response.getWriter().print("上传失败,文件太大,单个文件的最大限制是:"+sfu.getSizeMax()+"bytes!");
			}catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			response.getWriter().print("表单不是multipart/form-data,文件上传失败!");
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

  

文件上传至服务器

标签:0kb   web   bsp   block   string   用户   路径   port   private   

原文地址:http://www.cnblogs.com/goodtimealways/p/7105775.html


评论


亲,登录后才可以留言!