java实现文件上传下载的三种方法

JSP+Servlet

一、文件上传下载原理

在TCP/IP中,最早出现的文件上传机制是FTP。它是将文件由客户端发送到服务器的标准机制。但是在jsp编程中不能使用FTP方法来上传文件,这是由jsp的运行机制所决定的。

通过为表单元素设置Method=“post” enctype="multipart/form-data"属性,让表单提交的数据以二进制编码的方式提交,在接收此请求的Servlet中用二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传。

二、enctype属性的选择值范围

1、application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成url编码方式。

2、multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定的文件内容也封装到请求参数里。

3、text/plain:这种方式主要适用于直接通过表单发送邮件的方式。

代码内容

1.将文件读取到服务器指定目录下

2.获取文件内容的起止位置,和文件名称

3.将文件保存到项目的指定目录下

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//从request中获取输入流信息
		InputStream fileSource = request.getInputStream();
		//创建存储在服务器的路径信息
		String tempFileName = "H:/tempFile";
		//指向临时文件
		File tempFile = new File(tempFileName);
		//outPutStream输出流指向临时文件
		FileOutputStream outputStream = new FileOutputStream(tempFile); 
		//每次读取文件字节
		byte b[] = new byte[1024];
		int n;
		while((n=fileSource.read(b))!=-1){
			outputStream.write(b,0,n);
		}
		
		//关闭输出输入流
		fileSource.close();
		outputStream.close();
		
		//获取上传文件的名称
		RandomAccessFile randomFile = new RandomAccessFile(tempFile, "r");
		randomFile.readLine();  //获取第一行数据(对我们来说没有意义)
		String str = randomFile.readLine();  //获取第二行数据,内容为:Content-Disposition: form-data; name="myfile"; filename="C:\Users\lihf\Desktop\hello.txt"
		int beginIndex = str.lastIndexOf("\\")+1;
		int endIndex = str.lastIndexOf("\"");
		String fileName = str.substring(beginIndex, endIndex);
		
		//重新定位文件指针到头文件
		randomFile.seek(0);
		long startPosition=0;
		int i=1;
		//获取文件内容开始位置
		while((n=randomFile.readByte())!=-1&&i<=4){
			if(n=='\n'){
				startPosition = randomFile.getFilePointer();
				i++;
			}
		}
		startPosition = randomFile.getFilePointer() -1;
		//获取文件结束位置
		randomFile.seek(randomFile.length());  //文件指针定位到文件末尾
		long endPosition = randomFile.getFilePointer();
		int j=1;
		while(endPosition>=0&&j<=2){
			endPosition--;
			randomFile.seek(endPosition);
			if(randomFile.readByte()=='\n'){
				j++;
			}
		}
		endPosition = endPosition -1;
		
		//设置保存文件上传的路径
		String realPath = getServletContext().getRealPath("/")+"images";
		System.out.println("保存文件上传的路径:"+realPath);
		File fileupload = new File(realPath);
		if(!fileupload.exists()){
			fileupload.mkdir();  //创建此抽象路径名指定的目录。 
		}
		File saveFile = new File(realPath, fileName);
		RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
		//从临时文件中读取文件内容(根据文件起止位置获取)
		randomFile.seek(startPosition);
		while(startPosition

三、文件下载原理

1、step1:需要通过HttpServletResponse.setContentType方法设置Content-type头字段的值,为浏览器无法使用某种方式或激活某个程序来处理的MIME类型,例如,“application/octet-stream”或“application/x-msdownload”等。

2、step2:需要通过HttpServletResponse.setHeader方法设置Content-Disposition头的值为“attachment;filename=文件名”。

3、step3:读取下载文件,调用HttpServletResponse.getOutputStream方法返回的OutputStream对象来向客户端写入附件文件内容。

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取文件下载路径
		String path = getServletContext().getRealPath("/") + "images/";
		String filename = request.getParameter("filename");
		File file = new File(path + filename);
		if(file.exists()){
			//设置相应类型application/octet-stream
			response.setContentType("application/x-msdownload");
			//设置头信息
			response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
			InputStream inputStream = new FileInputStream(file);
			ServletOutputStream ouputStream = response.getOutputStream();
			byte b[] = new byte[1024];
			int n ;
			while((n = inputStream.read(b)) != -1){
				ouputStream.write(b,0,n);
			}
			//关闭流、释放资源
			ouputStream.close();
			inputStream.close();
		}else{
			request.setAttribute("errorResult", "文件不存在下载失败!");
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/01.jsp");
			dispatcher.forward(request, response);
		}
	}
JSP页面内容:

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


  
    
    My JSP '01.jsp' starting page
	
	
	    
	
	
	
	
	
  
  
  
  	
  
请选择上传图片:
下载hello.txt   ${errorResult}

图片预览

Large Image

SmartUpload实现上传下载

使用非常简单,直接引入SmartUpload的jar文件就可以啦

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 su = new SmartUpload();
		//初始化smartUpload
		su.initialize(getServletConfig(), request, response);
		//设置上传文件大小
		su.setMaxFileSize(1024*1024*10);
		//设置所有文件的大小
		su.setTotalMaxFileSize(102481024*100);
		//设置允许上传文件的类型
		su.setAllowedFilesList("txt,jpg,gif");
		String result = "上传能成功";
		try {
			//设置禁止上传文件类型
			su.setDeniedFilesList("jsp,rar");
			su.upload();
			int count = su.save(filePath);
			System.out.println("上传成功"+count+"文件!");
		} catch (Exception e) {
			result="上传文件失败!";
			if(e.getMessage().indexOf("1015")!=-1){				
				result = "上传文件失败:上传文件类型不正确!";
			}else if(e.getMessage().indexOf("1010")!=-1){
				result = "上传文件失败:上传文件类型不正确!";
			}else if(e.getMessage().indexOf("1105")!=-1){
				result = "上传文件失败:上传文件大小大于允许上传的最大值!";
			}else if(e.getMessage().indexOf("1110")!=-1){
				result = "上传文件失败:上传文件的总大小大于我们允许上传总大小的最大值!";
			}
			e.printStackTrace();
		}
		for(int i=0;i			com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
			System.out.println("表单当中name属性值:"+tempFile.getFieldName());
			System.out.println("上传文件名:"+tempFile.getFileName());
			System.out.println("上传文件的大小:"+tempFile.getSize());
			System.out.println("上传文件名拓展名:"+tempFile.getFileExt());
			System.out.println("上传文件的全名:"+tempFile.getFilePathName());
		}
		request.setAttribute("result",result);
		request.getRequestDispatcher("jsp/02.jsp").forward(request, response);
	}
jsp页面表单提交内容:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


  
    
    My JSP '02.jsp' starting page
	
	
	    
	
	
	
	
	
  
  
  	
上传文件1:
上传文件2:
上传文件3:
${result}

  下载:img5-lg.jpg
   

图片预览

Large Image

下载部分的代码

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String filename = request.getParameter("filename");
		SmartUpload su = new SmartUpload();
		su.initialize(getServletConfig(), request, response);
		su.setContentDisposition(null);
		try {
			su.downloadFile("/images/"+filename);
		} catch (SmartUploadException e) {
			e.printStackTrace();
		}
	}

Struts2实现上传下载:

上传jsp页面代码:

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


  
    
    My JSP '03.jsp' starting page
	
	
	    
	
	
	
	
	
  
  
  	

 文件上传

上传文件1:
上传文件2:
上传文件3:
${result}

图片预览

Large Image

struts.xml部分代码




    
    
    
	
    
			
					/jsp/03.jsp
					/jsp/error.jsp
					
					
						image/bmp,image/x-png,image/gif,image/pjpeg
						2M
					
					
			
			
				/images/img2-lg.jpg
				
					application/octet-stream
					inputStream
					
					attachment;filename="${downloadFileName}"
					8192
				
			
    
web.xml部分代码



  scxz
  
    UploadServlet
    com.lihf.servlet.UploadServlet
  
  
    DownloadServlet
    com.lihf.servlet.DownloadServlet
  
  
    SmartUploadServlet
    com.lihf.servlet.SmartUploadServlet
  
  
    SmartDownloadServlet
    com.lihf.servlet.SmartDownloadServlet
  
  
    UploadServlet
    /uploadServlet.do
  
  
    DownloadServlet
    /downloadServlet.do
  
  
    SmartUploadServlet
    /smartUploadServlet.do
  
  
    SmartDownloadServlet
    /smartDownloadServlet.do
  
  
    struts2
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  
  
      struts2
      /*
  
  
    index.jsp
  
action方法:

package com.lihf.action;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

	private List upload;
	private List uploadContentType;
	private List uploadFileName;
	private String result;
	public List getUpload() {
		return upload;
	}
	public void setUpload(List upload) {
		this.upload = upload;
	}
	public List getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(List uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public List getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(List uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getResult() {
		return result;
	}
	public void setResult(String result) {
		this.result = result;
	}
	@Override
	public String execute() throws Exception {
		String path = ServletActionContext.getServletContext().getRealPath("/images");
		File file = new File(path);
		if(!file.exists()){
			file.mkdir();
		}
		for(int i=0;i
下载:

action方法:

package com.lihf.action;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownLoadAction extends ActionSupport {
	public String inputPath;
	public String fileName;
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getInputPath() {
		return inputPath;
	}
	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}
	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
	public InputStream getInputStream() throws IOException{
		String path = ServletActionContext.getServletContext().getRealPath("/images");
		String filePath = path+"\\"+fileName;
		File file = new File(filePath);
		return FileUtils.openInputStream(file);
		//根据文件路径获取流信息固定下载文件使用方法
		//return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
	}
	public String getDownloadFileName(){
		//如果是中文的文件名称需要转码
		String downloadFileName = "";
		try {
			downloadFileName = URLEncoder.encode("文件下载.jpg","UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return downloadFileName;
	}
}
jsp页面:

文件下载(图片)













你可能感兴趣的:(Java基础)