Java EE文件上传

本文介绍Java EE中的三种文件上传方式

Java EE6 以上使用的方式(建议使用)

Java EE6以上可以不依赖任何第三方jar包完成文件上传
首先,编写一个简单的html,用于上传文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% String base =request.getContextPath()+"/"; //项目路径 %>
<html>
<head>
    <title></title>
</head>
<body>
  <form action="<%=base%>uploadFileServlet" method="post" enctype="multipart/form-data">
    <input type="file" name="attachment" />
    <input type="submit" value="提交" />
  </form>
</body>
</html>

然后是uploadFileServlet的内容,注意使用了注解,因此不需要再web.xml中配置了
package chapter3;


import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;

/** 通过表单上传文件
 * Created by chenhong on 15/9/15.
 */
@WebServlet(
        name="uploadFileServlet",
        urlPatterns = {"/uploadFileServlet"}
)
@MultipartConfig(
        fileSizeThreshold = 5_242_880 , // 5MB,小于5MB的上传文件将保存在内存中
        maxFileSize = 20_971_520L , //20MB, 禁止上传大小超过20MB的文件
        maxRequestSize = 41_943_040L //禁止大小超过40MB的请求
)

public class UploadFileServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part filePart =req.getPart("attachment"); //获取表单文件
        resp.setCharacterEncoding("UTF-8"); //设置返回数据的编码
        if(filePart!=null)
        {
            boolean success = processAttachment(filePart); //处理文件
            if(success)
            {
                resp.getWriter().append("文件上传成功");
            }
            else
            {
                resp.getWriter().append("文件上传失败");
            }
        }
        else
        {
            System.out.println("没有上传文件");
            resp.sendRedirect("upload.jsp");
        }
    }

    /**
     * 处理上传文件
     * @param filePart 上传文件
     * @return 文件是否上传成功
     */
    private boolean processAttachment(Part filePart) throws IOException
    {
        String type = getType(filePart.getContentType());//获取文件类型
        InputStream inputStream = filePart.getInputStream();
        File file = new File(getServletContext().getRealPath("/")+System.currentTimeMillis()+"."+type); //以 系统毫秒数 为新文件名
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
        int read ;
        final byte[] bytes = new byte[1024];

        while(  (read = inputStream.read(bytes))!=-1 )
        {
            bufferedOutputStream.write(bytes,0,read);
        }
        bufferedOutputStream.flush(); //一定要记得flush,否则可能会导致文件损坏
        return true;
    }

    /**
     * 获取文件类型
     * 如输入   image/png 则输出 png
     * @param contentType 输入类型
     * @return
     */
    private String getType(String contentType)
    {
        return  contentType.substring(contentType.indexOf("/")+1);
    }
}




SmartUpload方式

使用SmartUpload需要SmartUpload.jar包,可以使用下面的链接下载

链接1:https://code.google.com/p/assisted-learning/downloads/detail?name=smartupload.jar&can=2&q=

链接2:http://download.csdn.net/detail/ch717828/8836663 

下面通过一个上传文件的Demo来演示如何使用SmartUpload上传文件和普通表单

首先是一个待提交的表单:

 <form action="servlet/SmartUploadFile" method="post" enctype="multipart/form-data">
    	上传文件1:<input type="file" name="myfile1" /><br>
  		上传文件2:<input type="file" name="myfile2" /><br>
  		上传文件3:<input type="file" name="myfile3" /><br>
  		普通表单域:<input type="text" id="username" name="username" /><br>
  		<input type="submit" value="提交" />
    </form>

SmartUploadFile这个servlet使用了SmartUpload来处理上传
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;




public class SmartUploadFile extends HttpServlet {

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @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 doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		/*获取文件存储路径*/
		String filePath = getServletContext().getRealPath("/") + "images";
		File file = new File(filePath);
		if(!file.exists()){
			file.mkdir();
		}
		
		/*上传文件*/
		SmartUpload smartUpload = new SmartUpload();
		smartUpload.initialize(getServletConfig(), request, response);
		smartUpload.setMaxFileSize(1024*1024*10);
		smartUpload.setTotalMaxFileSize(1024*1024*100);
		smartUpload.setAllowedFilesList("txt,jpg,gif,png");
		int fileCount =0;//上传文件的数量
		try {
			smartUpload.setDeniedFilesList("rar,jsp,js");
			smartUpload.upload();
			for(int i=0;i<smartUpload.getFiles().getCount();i++)
			{
				com.jspsmart.upload.File f= smartUpload.getFiles().getFile(i);
				String ext =  f.getFileExt();   // 文件名后缀
				if (f.isMissing()) continue;  //如果没有上传文件,就跳过
				f.saveAs(filePath+File.separator+System.currentTimeMillis()+"."+ext); //以新文件名存储	
				System.out.println("上传文件"+System.currentTimeMillis()+i+"."+ext);
				fileCount++;
			}		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SmartUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/*获取普通表单域*/
		String username = smartUpload.getRequest().getParameter("username");
		System.out.println("用户名:"+username);

		request.setAttribute("responseStr",fileCount);
		request.getRequestDispatcher("/index.jsp").forward(request, response);
		
		
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
完整Demo:      http://download.csdn.net/detail/ch717828/8836695

Commons FileUpload方式

前端使用html, 后台用servlet , 完成普通表单和文件上传的功能

前端jsp内容如下

<form action="servlet/formservlet" method="post" enctype="multipart/form-data" >
    	<input type="text" id="username" name="username" /><br/>
    	<input type="file" id="file" name="file" /><br/>
    	<input type="submit" value="提交" />
    </form>

servlet 处理如下

首先是一个转换编码的函数

public String getStr(String str)
	{
		String s=null ;
		if(str!=null)
		{
			try {
				s = new String(str.getBytes("ISO8859-1"),"gb2312");
			} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("转码出现错误");
			}
		}
		return s;
	}

接下是doPost中的处理

request.setCharacterEncoding("gb2312");
		response.setContentType("text/html;charset=gb2312");
		//设置合法的后缀名
		final String[] allowedatt = new String[] {"doc","docx","html","htm"};
		//创建该对象 
	    DiskFileItemFactory factory = new DiskFileItemFactory();
	    //上传文件所用到的缓冲区大小,超过此缓冲区的部分将被写入到磁盘
	    factory.setSizeThreshold(4*1024);
	    //使用fileItemFactory为参数实例化一个ServletFileUpload对象   
	    ServletFileUpload upload = new ServletFileUpload(factory);
	     //要求上传的form-data数据不超过1000M
	    upload.setSizeMax(100*1024*1024);
	    //java.util.List实例来接收上传的表单数据和文件数据
	    List itemList;
		try {
			itemList = upload.parseRequest(request);
			//迭代list中的内容
		    Iterator it = itemList.iterator();
		    //循环list中的内容
		    while(it.hasNext())
		    {
		    	 //取出一个表单域
		    	 FileItem item =(FileItem) it.next();
		    	 //如果表单域是普通表单
		    	 if(item.isFormField())
		    	 {
		    		 //取出表单域的name,对应input的name
		    		String name = (String)item.getFieldName();
		    		//如果name的值是username
		    		if("username".equals(name))
		    		{
		    			//输出username表单中的值
		    			System.out.println(getStr(item.getString().trim()));
		    		}
		    		
		    	 }
		    	 //如果不是普通表单,则代表是文件上传的表单
		    	 else
		    	 {
		    		 //获取上传文件的名字
		    		 String totalNameatt = getStr(item.getName());
		    		 //获取文件的后缀名
		    		 String suffixatt =  totalNameatt.substring(totalNameatt.lastIndexOf(".") + 1);
		    		 //判断后缀名是否是我们允许上传的类型
		    		 boolean isValide=false;
		    		 for(int i=0;i<allowedatt.length;i++) {
			        		if(suffixatt.equals(allowedatt[i])){
			        			isValide=true;
			        		}
			        	}
		    		 //如果是不允许的类型,输出错误信息
		    		 if(!isValide)
		    		 {
		    			 System.out.println(totalNameatt+"该文件类型不在允许上传的范围内");
		    			 return ;
		    		 }
		    		 //如果是合法的,就保存该文件,文件名不变
		    		 else
		    		 {
		    			 //获取项目根目录
		    			 String rootPath = this.getServletConfig().getServletContext().getRealPath("/");  
		    			//要存储的文件的绝对路径
		    			 String file = rootPath +System.currentTimeMillis()+"."+suffixatt;
		    			 item.write(new File(file));
		    			 System.out.println("文件上传成功:"+file);
		    			 
		    		 }
		    		 
		    	 }
		    	
		    }
		    
		    
		    
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

完整的项目可以看 

http://download.csdn.net/detail/ch717828/8371595

参考:http://blog.csdn.net/hzc543806053/article/details/7524491




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值