码迷,mamicode.com
首页 > Web开发 > 详细

文件上传至服务器

时间:2017-07-02 13:45:19      阅读:209      评论:0      收藏:0      [点我收藏+]

标签: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"

例如

<form action="${pageContext.request.contextPath}/uploadServlet" method="post" enctype="multipart/form-data">
	用户名:<input type="text" name="username"/><br/>
	请选择文件:<input type="file" name="nfile"/><br/>
	<input type="submit" value="上传"/>
</form>

  

创建表单的步骤

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<FileItem> 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<String> 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<String> filTypes = Arrays.asList("jpg","png","gif","bmp");
			//限定单个文件的大小
			sfu.setSizeMax(1024*30);    //最大30KB
			try {
				List<FileItem> 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!