Servlet系列学习笔记15 --- Servlet文件上传和下载(二)jspSmartUpload组件

一、jspSmartUpload简介

       jspSmartUpload是由jspSmart开发的一个基于JSP的文件上传与下载的第三方组件。它提供了5个类,包含File、Files、Request、SmartUpload和SmartUploadException。其中SmartUploadException类是一个自定义异常类,这里我们就不介绍这个类。

1、File类

       此File类和java.io.File类,该类在com.jspsmart.upload软件包中。File类用于保存单个上传文件的相关信息,例如上传文件的文件名、文件大小、文件数据等,主要的方法如下:

方法

说明

void saveAs()

该方法用于保存文件

String getFieldName()

获取比当前上传文件所对应的表单项名称

String getFileName()

获取文件的文件名,该值不包含目录

String getFilePathName()

获取文件全名,获取的值是一个包含目录的完整文件名

String getFileExt()

获取文件扩展名,即后缀名

String getContentType()

获取文件MIME类型,例如“text/html”

String getContentString()

获取文件内容

int getSize()

获取文件大小,单位为byte

2、Files类

       Files类表示所有上传文件的集合,通过它可以得到上传文件的数目、大小等信息,主要方法如下:

方法

说明

int getCount()

获取上传文件的数目

File getFile(int index)

获取指定位置处的文件对象

Long getSize()

获取上传文件的总长度

Collection getCollection()

返回所有上传文件对象,以便被其他应用程序引用,

3、Request类

       Request类的功能等同于JSP内置对象的request。之所以提供Request类,是因为对于文件上传的表单,request对象无法获取表单输入域的值,而Reqeust对象却可以获取,主要方法如下:

方法

说明

String getParameter(String name)

获取表单中表单输入域name值

Enumeration getParameterNames()

获取表单中除输入域为file类型以外的所有表单元素名称

String[] getParameterValues(String name)

获取表单中多个名称为name的表单输入域的字符串数组

4、SmartUpload类

       SmartUpload类用于实现文件的上传和下载操作,主要方法如下:

方法

说明

void initialize(PageContext pageContext)

初始化,在使用SmartUpload对象时必须先调用方法,该方法进行了重载。此形式常用于JSP

void initialize(ServletConfig config, HttpServletRequest request, HttpResponse response)

初始化,此形式一般用于Servlet

void upload()

上传文件数据。上传操作一般初始化,再执行

Files getFiles()

获取全部上传的文件

setDeniedFilesList(String deniedFilesList)

禁止上传的文件扩展名,多个扩展名之间用逗号隔开。

int save(StringUri)

将全部上传的文件保存到指定目录中

int save(StringUri,int option)

同上。Opetion为保存选项,它有3个值,分别是SAVE_PHYSICAL、SAVE_VIRTUAL和SAVE_AUTO。第一个指定文件保存在操作系统根目录下,第二个指定文件保存在Web应用程序的根目录下,最后一个表示组件自动选择。

int getSize()

获取上传文件的总长度

void setMaxFileSize(long size)

设置每个上传文件的最大长度

void setMTotalMaxFileSize(long totalSize)

设置允许上传文件的总长度

void downloadFile(String source)

下载文件,source为下载文件的文件名

void downloadFile(String source,String contentType)

下载文件,contentType为文件内容类型(MIME格式的文件类型信息)

void downloadFile(String source, String contentType, String dest)

下载文件,dest是下载的文件另存为的文件名

void downloadFile(String source, String contentType, String dest,int blockSize)

下载文件,blockSize为存储读取的文件数据的字节数组大小,默认为65000

Request getRequest()

返回Request对象

二、文件上传

       在JSP页面中使用表单上传文件,需要对表单设置enctype="multipart/form-data"属性。

<form action="UpLoadServlet" method="post" enctype="multipart/form-data">
    <input type="file" name="picture"/><br/>
    <input type="file" name="vedio"/><br/>
    <input type="file" name="compressed"/><br/>
    <input type="file" name="textFile"/><br/>
    <input type="submit" name="UpLoad"/><br/>
</form>

       接下来是实现的业务逻辑了,具体代码如下

import java.util.Date;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class UploadServlet extends HttpServlet {
	//声明ServletConfig对象,作为initialize()方法的参数
	ServletConfig config;
	//初始化config对象
	public void init(ServletConfig config){
		this.config = config;
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("UTF-8");
		//【1】实例化一个SmartUpload对象
		SmartUpload su = new SmartUpload();
		//【2】初始化SmartUpload对象
		try{
			su.initialize(config, request, response);
		}catch(ServletException se){
			se.printStackTrace();
		}
		//【3】设置文件上传限制
		su.setAllowedFilesList("jpg,avi,zip,txt");
		//设置单个文件的最大字节数为2MB
		su.setMaxFileSize(1024*1024*2);
		//文件总的最大字节数为10MB
		su.setMaxFileSize(1024*1024*10);
		//【4】使用upload上传文件
		try{
			su.upload();
		}catch(ServletException se){
			se.printStackTrace();
		}catch(IOException ioe){
			ioe.printStackTrace();
		}catch(SmartUploadException sue){
			sue.printStackTrace();
		}
		//【5】保存文件
		//获取当前时间
		String Time = String.valueOf((new Date()).getTime());
		//创建Request对象
		Request req = su.getRequest();
		//获取全部上传文件
		Files files = su.getFiles();
		String extFile,fileName;	//文件后缀名, 文件重命名
		for(int i=0;i<files.getCount();i++){
			extFile = files.getFile(i).getFileExt();
			fileName = "C:/Users/LaoYe/Desktop/Files/" + Time + "." + extFile;
			try{
				//将当前遍历的文件保存到指定路径
				files.getFile(i).saveAs(fileName);
				System.out.println("----------------------------------------");
				System.out.println("当前文件在表单上的名称 = "+files.getFile(i).getFieldName());
				System.out.println("当前文件的扩展名 = "+files.getFile(i).getFileExt());
				System.out.println("当前文件的名称 = "+files.getFile(i).getFileName());
				System.out.println("当前文件的路径名 = "+files.getFile(i).getFilePathName());
				System.out.println("当前文件的MIME类型 = "+files.getFile(i).getContentType());
				System.out.println("用户是否选择了文件 = "+files.getFile(i).isMissing());
				System.out.println("文件大小 = "+files.getFile(i).getSize()+" Byte");
			}catch(IOException ioe){
				ioe.printStackTrace();
			}catch(SmartUploadException sue){
				sue.printStackTrace();
			}
		}
	}
}

       最终结果如下图所示

三、文件下载

       假设用户从File文件夹中下载一张图片,代码如下:

//声明ServletConfig对象,作为initialize()方法的参数
ServletConfig config;
//初始化config对象
public void init(ServletConfig config){
	this.config = config;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//【1】新建SmartUpload对象
	SmartUpload su = new SmartUpload();
	//【2】初始化
	su.initialize(config, request, response);
	//【3】设定contentDisponsition为null禁止浏览器自动打开文件
	su.setContentDisposition(null);
	//【4】下载文件
	try{
		su.downloadFile("G:/upload/wenen.txt");
	}catch(SmartUploadException e){
		e.printStackTrace();
	}
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
<%@ page language="java" contentType="text/html; charset=gbk"%> <%@ page pageEncoding="gbk"%> <%@ page import="com.jspsmart.upload.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gbk"> <title>Insert title here</title> </head> <body> <form action="upd2.jsp" method="post" enctype="multipart/form-data" name="form1"> <input type="file" name="file1"> <input type="text" name="title"> <input type="text" name="content"> <input type="submit" value="上传" > </form> </body> </html> 接受上传文件:okUpload.jsp 接受图片改变名称保存到指定目录并在网页上发布 接受参数值并显示在图片下面 <%@ page language="java" contentType="text/html; charset=gbk"%> <%@ page pageEncoding="gbk"%> <%@ page import="com.jspsmart.upload.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gbk"> <title>上传处理</title> </head> <body> <% SmartUpload su=new SmartUpload(); //初始化 su.initialize(pageContext); //上传 su.upload(); // 设置保存信息 String dir="upload"; //获取上传文件列表集合 Files files=su.getFiles(); for(int i=0;i<files.getCount();i++){ File file=files.getFile(i); //判断上传的是不是文件 if(!file.isMissing()){ //将获取的图片另存为文件名为new,后缀名从原是文件中获得 file.saveAs(dir+"/new."+file.getFileExt(),su.SAVE_VIRTUAL); //获取图片的客户端路径名 String name1=file.getFilePathName(); out.print("客户机原始路径名: "); out.print(name1); out.print("<br>"); out.print("服务器上的相对路径名: "); //构造服务器上的相对路径名 String name2=dir+"/"+"new.jpg"; out.print(name2); out.print("<br>"); %> <!-- 将上传后的图片发布 --> <img src="<%=name2 %>"> <% } } %> <!-- 获取传过来的非文件参数值 --> <%=su.getRequest().getParameter("title") %> <br> <%=su.getRequest().getParameter("content") %> <br> <br> </body> </html>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值