当前位置: 代码迷 >> Web前端 >> 文件下传的源码
  详细解决方案

文件下传的源码

热度:261   发布时间:2012-10-26 10:30:59.0
文件上传的源码

1.文件上传的jsp页面

<body>
<!--multipart/form-data:不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。  -->
<!-- 所谓不对字符编码:要是是上传文件,就是不对文件内容进行编码 -->
 <center>
<form name="fileupload" action="FileAction" method="POST" enctype="multipart/form-data">
 文件上传:<input  id="fileup1" name="fileup1" size="30" type="file" />
 <p></p>
 文件上传:<input  id="fileup2" name="fileup2" size="30" type="file" />
 <p></p>
 文件上传:<input  id="fileup3" name="fileup3" size="30" type="file" />
 <p></p>
  <input type="submit" name="file_sub" id="file_sub" value="上传"/>
 </form>
  </center>
</body>

?

2.web.xml文件配置

?

<servlet>
    <description></description>
    <display-name>FileAction</display-name>
    <servlet-name>FileAction</servlet-name>
    <servlet-class>testFileup.FileAction</servlet-class>
    <init-param>
      <param-name>uploadfilepath</param-name>
      <param-value>upload</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileAction</servlet-name>
    <url-pattern>/FileAction</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>FileDownLoad</display-name>
    <servlet-name>FileDownLoad</servlet-name>
    <servlet-class>testFileup.FileDownLoad</servlet-class>
    <init-param>
      <param-name>uploadfilepath</param-name>
      <param-value>upload</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileDownLoad</servlet-name>
    <url-pattern>/FileDownLoad</url-pattern>
  </servlet-mapping>

?

?

?

?3.文件上传部分(用的是org.apache.commons.fileupload)

?

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  
		//得到servlet配置中文件上传的路径
		String path=this.getInitParameter("uploadfilepath");
		path=this.getServletContext().getRealPath("/")+path;//获得文件存放的物理路径
		//path=request.getContextPath()+"\\"+path;
		System.out.println("文件存放的物理路径:"+path);
		//System.out.println("文件内容:"+(String)request.getParameter("fileup1"));
		//是否上传成功
		boolean state=false;
		java.util.List<File> files=new java.util.ArrayList();
		  
		try{
			//创建一个基于磁盘文件的工厂
			DiskFileItemFactory factory=new DiskFileItemFactory();
			//setRepository:Sets the directory used to temporarily store files that are larger than the configured size threshold. 
			factory.setRepository(new File(path));
			//setSizeThreshold:Sets the size threshold beyond which files are written directly to disk. 
			factory.setSizeThreshold(10);
			//创建一个文件处理器
			ServletFileUpload upload=new ServletFileUpload(factory);
			//解析请求
		    //Processes an RFC 1867 compliant multipart/form-data stream. 
			List items=upload.parseRequest(request);
			//处理文件上传项
			//Iterator iter=items.iterator();
			//while(iter.hasNext()){
			for(int i=0;i<items.size();i++){
				
				//FileItem:This class represents a file or form item that was received within a multipart/form-data POST request. 
				//FileItem item=(FileItem)iter.next();
				FileItem item=(FileItem)items.get(i);
				if(item.isFormField()){
					//true if the instance represents a simple form field;
					//普通请求,可以接受请求中的其他参数
				}else{
					//文件上传请求
					//获得文件上传名
					String filename=item.getName();
					//filename在IE浏览器获得是具体的文件上传的物理地址,如C:\Documents and Settings\lilang\桌面\5单元-javaWEB开发-13\14.实战报表:jFreeChart,cewolf,iText,jExcel.doc
					//在firefox获得的是文件的名字,如:2.JSTL应用讲解.doc
					System.out.println("文件全名:"+filename);
					if(!filename.equals("")){
					int count=filename.lastIndexOf("\\");
					if(count>0){
						filename=filename.substring(count);
					}else{
						filename="\\"+filename;
					}
					File temf=new File(path+filename);
					System.out.println("保存的路径为:"+temf.getAbsolutePath());
					//将文件写入服务器的目录上
					item.write(temf);
					files.add(temf);
					state=true;
					}
				}
				
				
			}
		}catch(Exception ep){
			ep.printStackTrace();
			
		}
		
		response.setContentType("text/html;charset=gbk");
		PrintWriter out=response.getWriter();
		if(state){
		while(files.size()>0){
			File file=files.remove(0);
			String filePath=file.getParentFile().getName()+"/"+file.getName();
			System.out.println("连接的文件路径:"+filePath);
			//out.println("<br><a href=\""+filePath+"\">"+file.getName()+"</a>");//不以io输出流来下载文件,直接在浏览器打开			
			String filename=file.getName();
			System.out.println("FileAction--文件名:"+filename);			
			out.println("<br><a href=\"FileDownLoad?filename="+filename+"\">"+file.getName()+"</a>");
			
		}// end while
		
		
		
		}
		

?4.文件下载部分

?

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("GB2312");

		String filename=request.getParameter("filename");
		filename=new String(filename.getBytes("ISO-8859-1"));
		System.out.println("获得的文件名:"+filename);
		//filename=URLDecoder.decode(filename,"UTF-8");
		//System.out.println("文件名:"+filename);
		String filePath=this.getServletContext().getRealPath("/")+this.getInitParameter("uploadfilepath")+"\\"+filename;
		System.out.println("要下载的文件物理路径:"+filePath);
		 response.reset();//可以加也可以不加
	      response.setContentType("application/x-download");
	      String filedownload =filePath;//提供下载的文件的物理路径
	      String filedisplay = filename;//文件下载路径
	      filedisplay =URLEncoder.encode(filedisplay,"UTF-8");
	      response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);

	      ServletOutputStream outp = null;
	      FileInputStream in = null;
	      try
	      {
	          outp = response.getOutputStream();
	          in = new FileInputStream(filedownload);

	          byte[] b = new byte[in.available()];
	          int t = 0;

	          while((t= in.read(b)) > 0)
	          {
	              outp.write(b, 0, t);
	          }
	          outp.flush();
	      }
	      catch(Exception e)
	      {
	          System.out.println("Error!");
	          e.printStackTrace();
	      }
	      finally
	      {
	          if(in != null)
	          {
	              in.close();
	              in = null;
	          }
	          if(outp != null)
	          {
	              outp.close();
	              outp = null;
	          }
	      }
	}
  相关解决方案