首页 > 代码库 > java上传文件

java上传文件

FileUpload下载地址:
 
  http://commons.apache.org/fileupload/
 
  下载:commons-fileupload-1.2.2-bin.zip    得到:commons-fileupload-1.2.2.jar
 
  http://commons.apache.org/io/
 
  下载:commons-io-1.4-bin.zip       得到:commons-io-1.4.jar

<!--将文件作为一种数据格式;-->
<!--注意:1.method="post"  2.enctype="multipart/form-data"-->
<html>
<form id="form" name="form" method="post" action="upload.action" enctype="multipart/form-data">
  <table >
  <tr>
      <td >
      <input  type="file" style="font-size:14px" name="filename" />
      </td>
  </tr>
  <tr>
      <td >
      <input type="submit" style="font-size:14px" value=http://www.mamicode.com/"上传文件"  />>


 

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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;


public class UploadServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			
			req.setCharacterEncoding("gbk");
			resp.setContentType("text/html;charset=gbk");
			PrintWriter out = resp.getWriter();
		    //磁盘文件工厂类;
		 	  DiskFileItemFactory factory = new DiskFileItemFactory();
		 	  //关联关系创建ServletFileUpload类;
		 	  ServletFileUpload upload = new ServletFileUpload(factory);
		  	  List<FileItem> items;
			try {
			  //将req中的数据放入表单域;
				items = upload.parseRequest(req);
				for(FileItem item : items){
				//判断是否是文件
					if(!item.isFormField()) {
							//文件名称;
							String filename = item.getName();
							//前缀路径;
							//某些浏览器会将文件的绝对路径全部提交;(ie)Y (chrome)N
						    filename = filename.substring(filename.lastIndexOf("\\")+1);
							//在WebRoot下创建一个uploads文件夹;
							//找到服务器上的路径upload文件夹;
							File file = new File(req.getServletContext().getRealPath("uploads")+File.separator+filename);
							//文件的二进制已经在item对象中,导入file文件;
							item.write(file);
							out.print("<html><center >上传成功,3秒后跳转!</center></html>");
							return ;
				  }
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			out.print("<html><center>上传失败!</center></html>");

	} 
}


web.xml

web.xml
   <servlet>
  	<servlet-name>upload</servlet-name>
  	 <servlet-class>cn.lh.web.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	 <servlet-name>upload</servlet-name>
   	 <url-pattern>/upload.action</url-pattern>
  </servlet-mapping>


 

java上传文件