欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【WebMail】利用commons.fileupload组件进行文件上传

程序员文章站 2022-07-13 22:45:40
...

利用commons.fileupload组件进行文件上传,首先要把下面的两个包导入web工程

Servlet:

 

 

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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * @author $KangMiao$
 * 文件上传
 */
public class UploadServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			req.setCharacterEncoding("UTF-8");
			resp.setCharacterEncoding("UTF-8");
			//获得一个文件上传对象
			DiskFileItemFactory factory = 
				new DiskFileItemFactory();
			ServletFileUpload sfu = 
			new ServletFileUpload(factory);
	    	//获得所有request请求
			List<FileItem> list = sfu.parseRequest(req);
			for (FileItem item : list) {
				if(item.isFormField()){  //判断参数是否为文件类型
					System.out.println("非文件类型数据:"
							+item.getFieldName()+"--"
							+item.getName());
				}else{
					System.out.println("name:"+item.getName()); //获得上传文件路径
					System.out.println("fileName:"+item.getFieldName());
					System.out.println("contentType:"+item.getContentType()); //获得上传文件类型
					System.out.println("size:"+item.getSize());  //上传文件大小
					
					String fromPath = item.getName();
					//获得保存文件的绝对路径
					String savePath = this.getServletContext().
					                  getRealPath("/")+"userfile";
					File fromFile = new File(fromPath);
					File toFile = new File(savePath,fromFile.getName());
					item.write(toFile);
					
 				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

 

 

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>文件上传</title>
    
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
   <form action="upfile" method="post" enctype="multipart/form-data">
    <input type="text" name="user">
    文件上传:<input type="file" name="file1">
    <input type="file" name="file2">
    <input  type="submit" value="上传"> 
    </form>
    <br>
    <a href="downfile">文件列表</a>
  </body>
</html>