java web学习基础(五) 文件上传 SmartUpload

SmartUpload是由www.jspsmart.com网站开发的一套上传组件包,可以轻松实现文件的上传和下载功能。

SmartUpload本身是一个系统提供的jar包。导入就可以使用。

要像进行上传还必须使用HTML中提供的file控件,而且form必须进行使用enctype进行封装。

例如在form中加入<from enctype="multipart/form-data"  aciton="smart.jsp">

<input type="file" name="pic">

</from>

被跳转页面引用:

<% SmartUpload smart=new SmartUpload();//实例化组件

smart.initializa(pageContext);//初始化上传操作

smart.upload();//上传准备

smart.save("upload");//保存到该jsp目录下的upload文件夹内。

%>


如果要上传文件必须封装,但是当一个表单使用了enctype封装后,其他的非表单控件的内容就无法通过request内置对象获得,,此时必须通过SmartUpload类中提供的getRequest()方法取得全部的请求参数。

例如:<form action="index.jsp">

name:<input type="text" name="username">

pic:<input type="file" name="pic">

</from>

被跳转index.jsp页面 注意smartupload的代码顺序

<% SmartUpload smart=new SmartUpload();//实例化组件

smart.initializa(pageContext);//初始化上传操作

smart.upload();//上传准备

String name=smart.getRequest().getParameter("username");//通过这句话获得name值。

smart.save("upload");//保存到该jsp目录下的upload文件夹内。

%>


下一步是为文件自动命名,以时间和文件后缀命名,

下面两句直接可以获得当前系统时间,并把时间字符串赋值给time;

               SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String time=sd.format(new Date());

下面是获得上传文件的后缀

String ext=smart.getFiles().getFile(0).getFileExt();

接着拼凑文件名称:

String filename=timt+"."+ext;

最后一步是保存文件

smart.getFiles().getFile(0).savaAs(getServletContext().getRealPath("/")+"upload" +java.io.File.separator+filename);

注意路径的问题upload文件夹是在  webcontent文件夹下建立的。

我们可以用下面的代码把表单的文字和图片显示出来在网页上。

<%=name %>
<img  src="upload/<%=filename%>">   //此处的路径也需要特别注意。





我们也可以实现多个文件上传

例如

照片1:<input type="file " name="pic1">

照片2:<input type="file"  name="pic2">

 在处理页面我们可以用smart.getFiles().getCount();获得文件的数量;

for (int i=0; i<smart.getFiles().getCount(); i++)

{

String ext=smart.getFiles().getFile(i).getFileExt();

String filename=time+"."+ext;

smart.getFiles().getFile(i).saveAs(getServletContext().getRealPath("/")+"upload" +java.io.File.separatro+filename);

}

这样实现了多文件上传。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值