Java web 文件上传下载(Eclipse + Tomcat)

1. firstly  我们需要准备好两个包 分别为 commons-io-1.3.2.jar 以及   commons-fileupload-1.2.1.jar 

2. 我们要明确实施的方式 

Web页面使用file标签上传一个文件  以form标签来包装  再通过servlet的方式将form数据转发到后台Servlet

后台Servlet通过request获取到form的数据之后  找到真实文件  指定服务器端的一个路径  然后将真实文件以流的方式写入到指定路径下

掉转到原上传页面将路径以参数的形式传递到上传页面上

上传页面根据给定的路径来加载相关的文件

3.具体的代码文件

首先是jsp,index.jsp

注意这里的<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>避免页面中文乱码

还有<%request.setCharacterEncoding("UTF-8");%>  保证request解析到的中文不会乱码

 

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


  
    
    
    My JSP 'index.jsp' starting page
    
    
	
	
	    
	
	
	
	
	
	
	
  
  
  
    With this page, you can upload your file.     
    
username :

 

 

第二部分web,xml  用来对servlet前后台交互的设置

	


  FileUploadDownLoad
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  
  	UploadServlet
  	com.java.servlet.UploadHandleServlet
  
  
  
      UploadServlet
      /upload
     
  

 

 

 

 

第三部分  Servlet类  UploadHandleServlet

 

 

package com.java.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 
 * @author zero
 *
 */
public class UploadHandleServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
System.out.println("get the request from the page....");
		
		String path = req.getRealPath("/upload");//create a path to save the file uploaded
		
System.out.println(path);
		
		File file = new File(path);
		file.mkdirs();
		  
        DiskFileItemFactory factory = new DiskFileItemFactory();  
        factory.setRepository(file);   //set temporary file
  		factory.setSizeThreshold(1024*1024);//set temporary file's size
  		
  		ServletFileUpload upload = new ServletFileUpload(factory);
  		upload.setHeaderEncoding("UTF-8");//set the encoding language
  		
  		try {
  			List list = (List)upload.parseRequest(req);  //get the item list from the from label
  	
  			for(FileItem item : list) {
  				String name = item.getFieldName();   //get the file(field or real file)'s name
  				if(item.isFormField()) {
System.out.println("just a simple field....");
				String value = item.getString();
System.out.println(name + " = " + value );
  					req.setAttribute(name, value);
  				}else{
  					 String value = item.getName();//this item is real file
  					 
System.out.println("got a real file");  	

  					 int start = value.lastIndexOf("\\");
  					 String filename = value.substring(start+1);//获得真正的文件名字,通常这一步转化只有在使用Opera浏览器时才需要使用
  					 
System.out.println("file name : " + filename);
  					
  					 req.setAttribute(name,  filename);
  					
  					 File f1 = new File(path,filename);
  					 
  					 OutputStream os = new FileOutputStream(f1);
  					 InputStream is = item.getInputStream();
  					 
  					 byte[] buffer = new byte[400];
  					 int length;
  					 
  					 while((length = is.read(buffer))!=-1) {
  						 os.write(buffer, 0, length);
  					 }
  					 
  					 is.close();
  					 os.close();
System.out.println("generate a file in the server.....");
  		  	  		req.getRequestDispatcher("index.jsp?&fileName=upload/" + filename).forward(req, resp);
  				}
  			}
  		}catch(Exception e) {
  			e.printStackTrace();
  		}
  		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp){
		try {
			doGet(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

 

几个要点需要注意:

来确保匿名上载文件的正确编码

upload.setHeaderEncoding("UTF-8");//set the encoding language保证Servlet端中文解码的正确性

上传的文件会被保存在D:\常用工具软件\ApacheServer\apache-tomcat-8.0.8\webapps\FileUploadDownLoad\upload这个目录下

前面的是安装的tomcat所在的目录  当然了也可以用MyEclipse内置的tomcat来运行项目,但是路径会有区别

资源页http://download.csdn.net/detail/lin19931006/8548537免费的哦

Java web 文件上传下载(Eclipse + Tomcat)_第1张图片Java web 文件上传下载(Eclipse + Tomcat)_第2张图片

 

你可能感兴趣的:(网站设计)