jspSmartUpload--文件上传与下载组件的应用----文件上传、下载、删除

一、安装与配置:将文件放到对于的包下;

二、主要类:1、File类:用于保存单个上传文件的相关信息,如上传文件的文件名、文件大小、文件数据等。

2、Files类:存储了所有上传的文件,通过类中的方法可获得上传文件的数量和总长度等信息。

3、Request类:因为当Form表单用来实现文件上传时,通过JSP的内置对象request的getParameter()方法无法获取其他表单项的值,所以提供了该类来获取。

4、SmartUpload类:用于实现文件的上传与下载操作。

把这个经典的smartUpload包放到src下合适的位置。

然后在页面中调用类的相关方法就可以了。

------uploadmanager.jsp-------------这个页面是提交页面,from表单提交-

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="java.sql.*"%>
<%@ page import="grad.util.course.*"%>
<%@ page session="true" %>
<html>
<head><title></title>
<script language="javascript">
function doCheck(){
    if(upload.title.value==""){
      alert("请填写资源标题!");
      upload.title.focus();
      return false;
    }
    else if(upload.file.value==""){
      alert("请选择上传文件!");
      upload.file.focus();
      return false;
    }
    else if(upload.courseid.value=="0"){
      alert("请选择资源所属课程");
      upload.courseid.focus();
      return false;
    }
    else
      return true;
}
</script>
</head>
<body>
<%
if(((String)session.getAttribute("user_id")!=null)||((String)session.getAttribute("type")!="2")){
String auser_id=(String)session.getAttribute("user_id");
%>
<form name="upload" method="post" action="../uploadfile.jsp" enctype="multipart/form-data" οnsubmit="return doCheck()">
<table cellpadding="0" cellspacing="0" width="90%">
   <tr><td height="30" colspan=2 class=TableTitle2><span class="STYLE1">上传新资源:</span></td></tr>
   <tr><td height="25" align="right"><strong>资源标题:</strong></td>
       <td width="85%"><input type="text" name="title" size="30" ></td>
   </tr>
   <tr><td width="15%" height="25" align="right"><strong>文件:</strong></td>
       <td><input type="file" name="file" SIZE="20"></td>
   </tr>
   <tr><td width="15%" height="25" align="right"><strong>资源所属课程:</strong></td>
       <td><select name="courseid" size="1">
             <option value="0"></option>
        <%
            op_courseInfo opc=new op_courseInfo();
            ResultSet rs2=opc.getAllCoursenameByTeaid(auser_id);
            while(rs2.next()){
        %>
             <option value="<%=rs2.getString("课程号") %>"><%=rs2.getString("课程名")%></option>
        <%   
           }
        %>
         </select>
     </td>
</tr>
<tr><td>用户下载权限:</td><td>
         <select name="power" size="1">
            <option value="0" selected>不允许学生下载该资源</option>
            <option value="1">允许学生下载</option>
         </select>
     </td>
</tr>
<tr><td>&nbsp;</td><td><input type="submit" value="上传" name="submit" />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="reset" value="重置" name="reset"/>
</td></tr>
<tr><td>
     <input type="hidden" name="userid" value="<%=auser_id %>"/>
     </td></tr>
</table>  
</form>
<%
}
else{
out.print("你还没有登录或者没有权限进入,请<a href=../index.jsp target=_parent>返回首页登录</a>");
}
%>
</body>
</html>

*******uploadfile.jsp*****这个是处理提交的页面,由该页面实现文件的上传

<%@ page contentType="text/html;charset=gb2312" language="java" %>
<%@ page import="com.jspsmart.upload.*" %>
<%@ page import="grad.util.course.op_resourse" %>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
<jsp:useBean id="dbConn" class="grad.util.DBConn"></jsp:useBean>

<html>
<head>
    <title>updatepassword2</title>
   </head>
<body>
<hr size="1" width="100%">
<p>
<%
//定义目标目录
String destination="/ziliaojia/";
long maxsize=50*1024*1024;
try{
mySmartUpload.initialize(pageContext);    
mySmartUpload.setMaxFileSize(maxsize);     //设置每个上传文件的大小,最大为50M
mySmartUpload.setDeniedFilesList("exe,,bat,ini,tmp");//不允许上传的文件的扩展名
//文件上传
mySmartUpload.upload();
SmartFiles files=mySmartUpload.getFiles(); //获得所有的上传文件
//上传的情况统计
for (int i=0;i<files.getCount();i++){
   SmartFile myFile = mySmartUpload.getFiles().getFile(i);
   if (!myFile.isMissing()){
     //获得表单的内容
       String title = mySmartUpload.getRequest().getParameter("title"); //资源标题
       String acourseid=mySmartUpload.getRequest().getParameter("courseid");//资源所属课程号
       String csid = mySmartUpload.getRequest().getParameter("userid"); //资源发布人
       java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //获得系统当前时间,并将其格式化为yyyy-MM-dd HH:mm:ss   
       String anowdate= dateFormat.format(new java.util.Date(System.currentTimeMillis()));
       String spower=mySmartUpload.getRequest().getParameter("power"); //用户下载权限
       op_resourse opr=new op_resourse();
       int autoid=opr.getMaxId();//为了防止中文问题,把文件都以编号作为文件名
       String sname=autoid+"."+myFile.getFileExt();
       String sql="insert into 资源表(资源标题,资源名称,文件类型,后缀名,资源大小,资源发布人,资源所属课程号,资源权限,发布时间)values('"+title+"','"+sname+"','"+myFile.getContentType()+"','"+myFile.getFileExt()+"',"+myFile.getSize()+",'"+csid+"','"+acourseid+"','"+spower+"','"+anowdate+"')";
       boolean num=dbConn.executeSql(sql);
       if(num){
         myFile.saveAs(destination+sname,SmartFile.SAVEAS_VIRTUAL);
         out.println("文件上传成功!"+ "<BR>");
         out.println("文件名称= " + myFile.getFileName() + "<BR>");
         out.println("文件大小= " + myFile.getSize() + " Byte<BR>");
         out.println("文件扩展名= " + myFile.getFileExt() + "<BR>");
         out.println("文件路径名= " + myFile.getFilePathName() + "<BR>");
         out.println("文件类型= " + myFile.getContentType() + "<BR>");        
       }
       else if(!num){
         out.println("出错了,请检查输入!");
       }
    }//if (!myFile.isMissing()){
}//for (int i=0;i<files.getCount();i++){
}catch(Exception e){
   request.setAttribute("errors","文件上传失败!");
   e.printStackTrace();
}
out.println("<BR><a href=javascript:οnclick=history.go(-1)>返回</a><BR>");
%>
</p>
</body>
</html>

需要注意的地方:

1、在form表单页面,表单的method属性必须为post,并且必须设置enctype="myltipart/form-date"属性,<input type="file">标记实现的表单元素可用来选择文件,通过上面的属性设置后,Form表单中通用的表单元素如<input type="text">,在表单提交后,通过JSP的request内置的getParameter()方法将无法获取其值,可应用jspSmartUpload组件提供的Request类中的getParameter()方法获取。

2、创建接受表单,进行上传的jsp文件,在该jsp文件中调用jspSmartUpload组件进行文件上传。将文件上传到服务器,并且将文件的信息存储到了数据库中,如文件的实际名称,上传到服务器进行存储的文件名和文件类型等信息。所以,这里不能直接调用SmartUpload类的save()方法将上传的所有文件存储到服务器中,而应逐个获取以jspSmartUpload组件中的File类表示的单个文件,然后获取当前文件的相应信息并存储在数据库中,最好调用Files类的saveAs()方法保存文件。

3、实现文件下载:。通过“下载”连接进入dodown.jsp页面,在该页面调用jspSmartUpload组件进行文件下载。<a href="dodown.jsp?downfile=<%=filesave%>">下载</a>

-----------dodown.jsp----------------------页面关键代码

<%@ page contentType="text/html;charset=gb2312" %>
<jsp:useBean id="mydown" class="com.jspsmart.upload.SmartUpload"></jsp:useBean>

<%
String adownfile=request.getParameter("downfile");
String filepath="webapps/netteaching/ziliaojia/";
String downfile=filepath+adownfile;
try{
   response.reset();
   out.clear();
   out=pageContext.pushBody();
   mydown.initialize(pageContext);
   mydown.setContentDisposition(null);
   mydown.downloadFile(downfile);
}catch(Exception e){
   String errors="<li>文件下载失败,请重新下载!</li>";
   request.setAttribute("errors",errors);
   RequestDispatcher rd=request.getRequestDispatcher("fileManager.jsp");
   rd.forward(request,response);
}
%>

注意:在SmartUpload类用于下载文件的downloadFile()方法中,最终通过response.getOutputStream().write()方法将要下载的文件数据写入到相应客户的输出流提供给用户进行下载,所以还要编写如下代码:

response.reset();

out.clear();

out=pageContext.pushBody();

否则,将抛出下面的异常:getOutputStream() has already been called for this response

4、删除文件:filedelete.jsp

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="java.io.*"%>
<%@ page import="grad.util.course.op_resourse" %>
<%@ page session="true" %>
<html>
<head>
    <title>fileDeleteSubmit</title>
</head>
<body>
<%
    //删除资源
    int rsid=Integer.parseInt(request.getParameter("ID"));
    String sfile=request.getParameter("filename");
    op_resourse opr=new op_resourse();
    boolean bol=opr.delResourse(rsid); //删除表中记录
    if(bol){
      out.println("删除成功!");
    }
    String filepath="webapps/netteaching/ziliaojia/";
    String fullfile=filepath+sfile;
    File f=new File(fullfile);
    boolean bol2=f.delete();   //删除对应的文件
    if(bol2){
       out.println("删除文件成功");
    }
   
    response.setHeader("Refresh","1; URL=fileManager.jsp");//1秒后自动跳转页面
%>

</body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值