Jquery上传插件uploadify的使用(JSP)版

本文详细介绍了如何使用uploadify插件版本3.1实现文件上传功能,包括项目搭建、导入所需包、JSP页面代码编写、后台处理的servlet配置以及上传过程的JavaScript实现。此外,还提供了上传文件的示例代码,帮助开发者快速上手。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天,突然想研究下那个uploadify插件,在网上搜索好多资料,发现千奇百怪,可能是版本问题,关于服务端处理脚本我发现了两种说法,一种是通过‘script’来设置的,另一种是用‘uploadify’来设置的。我下面演示的是使用后者来设置服务端处理脚本的,插件版本为3.1版本

  1. 准备好uploadify 3.1版本的插件
  2. 建立一个web项目,并导入所需要的包,包括三个包(commons-fileupload-1.2.2.jar,commons-io-2.0.1.jar,commons-lang-2.5.jar)
  3. 写好JSP页面代码
  4. 创建后台处理的servlet
  5. 配置web.xml
结构目录图:



红色圈住的部分本来应该放在css文件夹下,不过我喜欢将所有的uploadify插件的东西都放在一块。

index.jsp代码如下

<%@ page language="java" contentType="text/html; charset=utf-8"%>  
<%  
        String path = request.getContextPath();  
        String basePath = request.getScheme() + "://"  
                + request.getServerName() + ":" + request.getServerPort()  
                + path + "/";  
    %>      
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    <html>  
      <head>  
        <base href="<%=basePath%>">  
          
        <title>文件上传</title>  
          
     <link href="js/uploadify/uploadify.css" rel="stylesheet" type="text/css" />  
     <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>  
     <script type="text/javascript" src="js/uploadify/jquery.uploadify-3.1.min.js"></script>  
    <script type="text/javascript">  
    $(document).ready(function() {  
     $("#uploadify").uploadify({  
                    'auto'           : false,  
                    'swf'            : '<%=path%>/js/uploadify/uploadify.swf',  
                    'uploader'       : '<%=path%>/scripts/uploadify',//后台处理的请求  
                    'queueID'        : 'fileQueue',//与下面的id对应  
                    'queueSizeLimit' :3,  
                    'fileTypeDesc'   : 'rar文件或zip文件',  
                    'fileTypeExts'   : '*.rar;*.zip', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc  
                    'multi'          : true,  
                    'buttonText'     : '上传'  
     });  
    });  
    </script>  
     </head>  
    <body>  
            <div id="fileQueue"></div>  
            <input type="file" name="uploadify" id="uploadify" />  
            <p>  
                <a href="javascript:$('#uploadify').uploadify('upload')">开始上传</a>   
                <a href="javascript:$('#uploadify').uplaodify('cancel','*')">取消上传</a>  
            </p>  
      </body>  
    </html>  

Uploadify.java代码如下:
package com.rh.core.upload;
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.Iterator;  
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.disk.DiskFileItem;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  
import org.apache.commons.fileupload.util.Streams;  
  
public class Uploadify extends HttpServlet{  
    private static final long serialVersionUID = 1L;    
        
    /**  
     * 实现多文件的同时上传  
     */     
    public void doGet(HttpServletRequest request,    
            HttpServletResponse response) throws ServletException, IOException {    
            
        //设置接收的编码格式    
        request.setCharacterEncoding("UTF-8");    
        Date date = new Date();//获取当前时间    
        SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmss");    
        SimpleDateFormat sdfFolder = new SimpleDateFormat("yyMM");    
        String newfileName = sdfFileName.format(date);//文件名称    
        String fileRealPath = "";//文件存放真实地址    
            
        String fileRealResistPath = "";//文件存放真实相对路径    
            
        //名称  界面编码 必须 和request 保存一致..否则乱码    
        String name = request.getParameter("name");    
                
             
        String firstFileName="";    
        // 获得容器中上传文件夹所在的物理路径    
        String savePath = this.getServletConfig().getServletContext().getRealPath("/") + "uploads\\" + newfileName +"\\";    
        System.out.println("路径" + savePath+"; name:"+name);    
        File file = new File(savePath);    
        if (!file.isDirectory()) {    
            file.mkdirs();    
        }    
    
        try {    
            DiskFileItemFactory fac = new DiskFileItemFactory();    
            ServletFileUpload upload = new ServletFileUpload(fac);    
            upload.setHeaderEncoding("UTF-8");    
            // 获取多个上传文件    
            List fileList = fileList = upload.parseRequest(request);    
            // 遍历上传文件写入磁盘    
            Iterator it = fileList.iterator();    
            while (it.hasNext()) {    
                Object obit = it.next();  
                if(obit instanceof DiskFileItem){  
                    System.out.println("xxxxxxxxxxxxx");  
                    DiskFileItem item = (DiskFileItem) obit;    
                        
                    // 如果item是文件上传表单域       
                    // 获得文件名及路径       
                    String fileName = item.getName();    
                    if (fileName != null) {    
                        firstFileName=item.getName().substring(item.getName().lastIndexOf("\\")+1);    
                        String formatName = firstFileName.substring(firstFileName.lastIndexOf("."));//获取文件后缀名    
                        fileRealPath = savePath + newfileName+ formatName;//文件存放真实地址    
                            
                        BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 获得文件输入流    
                        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(fileRealPath)));// 获得文件输出流    
                        Streams.copy(in, outStream, true);// 开始把文件写到你指定的上传文件夹    
                        //上传成功,则插入数据库    
                        if (new File(fileRealPath).exists()) {    
                            //虚拟路径赋值    
                            fileRealResistPath=sdfFolder.format(date)+"/"+fileRealPath.substring(fileRealPath.lastIndexOf("\\")+1);    
                            //保存到数据库    
                            System.out.println("保存到数据库:");    
                            System.out.println("name:"+name);    
                            System.out.println("虚拟路径:"+fileRealResistPath);    
                        }    
                             
                    }     
                }  
            }     
        } catch (org.apache.commons.fileupload.FileUploadException ex) {  
           ex.printStackTrace();    
           System.out.println("没有上传文件");    
           return;    
        }     
       response.getWriter().write("1");    
            
    }    
     
    public void doPost(HttpServletRequest req, HttpServletResponse resp)    
            throws ServletException, IOException {    
        doGet(req, resp);    
    }    
}  
web.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	 <servlet>    
     <servlet-name>Uploadify</servlet-name>    
     <servlet-class>com.rh.core.upload.Uploadify</servlet-class>    
    </servlet>    
    <servlet-mapping>    
     <servlet-name>Uploadify</servlet-name>    
     <url-pattern>/scripts/uploadify</url-pattern>    
    </servlet-mapping>  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

OK,以上成功案例参考了别人的博客,该博客链接为 点击打开链接



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值