zoukankan      html  css  js  c++  java
  • plupload2.1.2文件合并

    1.前端

    (1)依赖文件:

        <link type="text/css" rel="stylesheet" href="~/Content/plupload_2_1_2/jquery-ui.min.css" media="screen" />
        <link type="text/css" rel="stylesheet" href="~/Content/plupload_2_1_2/jquery.ui.plupload/css/jquery.ui.plupload.css" media="screen" />
        <script type="text/javascript" src="~/Content/plupload_2_1_2/jquery.js" charset="UTF-8"></script>
        <script type="text/javascript" src="~/Content/plupload_2_1_2/jquery-ui.min.js" charset="UTF-8"></script>
        <script type="text/javascript" src="~/Content/plupload_2_1_2/plupload.full.min.js" charset="UTF-8"></script>
        <script type="text/javascript" src="~/Content/plupload_2_1_2/jquery.ui.plupload/jquery.ui.plupload.min.js" ></script>
        <script type="text/javascript" src="~/Content/plupload_2_1_2/zh_CN.js" charset="UTF-8"></script>

    (2)HTML

        <form id="uploader">
            <input type="text" name="filename" value="" />
        </form>

    (3)js

       <script type="text/javascript">
            //文件名不能相同
            $(function () {
                $("#uploader").plupload({
                    // General settings
                    runtimes: 'gears,flash,silverlight,browserplus,html5',
                    url: '/upload/plupload',
                    max_file_size: '6079mb',
                    max_file_count: 20,
                    chunk_size: '2048kb',
                    unique_names: false,
                    init: {
    
                        // Resize images on clientside if we can
                        //resize: {  320, height: 240, quality: 90 },
                        rename: false, // 是否重命名文件
                        sortable: true, // Sort files
                        dragdrop: true, //启用文件到小部件能够拖放(操作)(目前唯一HTML5支持)
                        filters: [
                            { title: "Image files", extensions: "jpg,gif,png,txt,sql" },
                            { title: "music", extensions: "avi,mp4,mp3,exe,zip" }
                        ],
                        views: {
                            list: true,
                            thumbs: true, // Show thumbs
                            active: 'thumbs'
                        },
                        // Flash settings
                        flash_xap_url: '~/Content/upload/js/Moxie.xap',
                        // Silverlight settings
                        silverlight_xap_url: '~/Content/upload/js/Moxie.xap',
                        BeforeUpload: function (uploader, file) {
                            //alert(123)
                            //var $li = $('#uploader_filelist li').hasClass('plupload_file')[0]
                            //var value = $($li).find('div.plupload_file_name').attr('title')
                            //alert($li)
                        },
                        QueueChanged: function () {
                            var $li = $('#uploader_filelist li')
                            console.log($li)
                        },
                        FileUploaded: function (uploader, file, responseObject) {
                            //console.log(responseObject)
                            //alert(curDirID)
                            //initData(responseObject.response.curDirId)
                            $.ajax({
                                url: '/Cloudpan/GetCurdir',
                                type: 'post',
                                success: function (id) {
                                    initData(id)
                                }
                            })
                        }
                    }
                });
            });
        </script>
    View Code

    2.后台

      后台可以使用FileInputStream的构造方法追加文件内容。plupload使用“multipart/form-data”这种表单上传文件,其中每一个分块会发出一次请求,表单中有两个字段,分别是“chunk”和“chunks”,其中“chunk”是当前正在处理的文件分块的序号(从0开始计数),而“chunks”则是文件的分块总数。

    (1).net

      asp.net MVC【有bug】

    /// <summary>
    /// 文件上传
    /// </summary>
    /// <returns></returns> 
    public JsonResult plupload(string name)
    { 
        string msg = string.Empty;
        string strchunk = Request["chunk"];
        string strchunks = Request["chunks"];
        int chunk = 0;
        int chunks = 0;
        int.TryParse(strchunk, out chunk);
        int.TryParse(strchunks, out chunks);
    
        foreach (string upload in Request.Files)
        {
            if (upload != null && upload.Trim() != "")
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "Temp\";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                System.Web.HttpPostedFileBase postedFile = Request.Files[upload];
                string filename1 = Path.GetFileName(postedFile.FileName);
                string filename = name;
               
                string newFileName = filename;
                if (chunks>1)
                {
                    newFileName = chunk + "_" + filename;
                }
                string fileNamePath = path + newFileName;
                postedFile.SaveAs(fileNamePath);
    
                if (chunks>1 && chunk + 1 == chunks)
                {
                    using (FileStream fsw = new FileStream(path + filename, FileMode.Create, FileAccess.Write))
                    {
                        BinaryWriter bw = new BinaryWriter(fsw);
                        // 遍历文件合并 
                        for (int i = 0; i < chunks; i++)
                        {
                            bw.Write(System.IO.File.ReadAllBytes(path + i.ToString() + "_" + filename));
                            bw.Flush();
                        }
                    }
    
                }
                 
            }
        } 
        return Json(new { jsonrpc = "2.0", result = "", id = "id" });
       
    }

    (2)servlet

    config.properties:

    uploadPath=/upload/images
    package cn.getword.servlet;
    
    import com.alibaba.fastjson.JSON;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.io.FileUtils;
    import org.apache.commons.io.FilenameUtils;
    
    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 java.io.*;
    import java.util.*;
    
    @WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload/plupload.do"})
    public class FileUploadServlet extends HttpServlet {
        String uploadPath;
        private static final ResourceBundle bundle = ResourceBundle.getBundle( "config" );
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setCharacterEncoding( "UTF-8" );
            Integer chunk = null; /* 分割块数 */
            Integer chunks = null; /* 总分割数 */
            String tempFileName = null; /* 临时文件名 */
            String newFileName = null; /* 最后合并后的新文件名 */
            BufferedOutputStream    outputStream    = null;
    
    
    
            /* System.out.println(FileUtils.getTempDirectoryPath()); */
            uploadPath = request.getServletContext().getRealPath( bundle.getString( "uploadPath" ) );
            File up = new File( uploadPath );
            if ( !up.exists() )
            {
                up.mkdir();
            }
    
            if ( ServletFileUpload.isMultipartContent( request ) )
            {
                try {
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    factory.setSizeThreshold( 1024 );
                    /* factory.setRepository(new File(repositoryPath));// 设置临时目录 */
                    ServletFileUpload upload = new ServletFileUpload( factory );
                    upload.setHeaderEncoding( "UTF-8" );
                    /* upload.setSizeMax(5 * 1024 * 1024);// 设置附件最大大小,超过这个大小上传会不成功 */
                    List<FileItem> items = upload.parseRequest( request );
                    for ( FileItem item : items ){
                        if ( item.isFormField() ) /* 是文本域 */
                        {
                            if ( item.getFieldName().equals( "name" ) )
                            {
                                tempFileName = item.getString();
                                /* System.out.println("临时文件名:" + tempFileName); */
                            } else if ( item.getFieldName().equals( "chunk" ) )
                            {
                                chunk = Integer.parseInt( item.getString() );
                                /* System.out.println("当前文件块:" + (chunk + 1)); */
                            } else if ( item.getFieldName().equals( "chunks" ) )
                            {
                                chunks = Integer.parseInt( item.getString() );
                                /* System.out.println("文件总分块:" + chunks); */
                            }
                        } else { /* 如果是文件类型 */
                            if ( tempFileName != null )
                            {
                                String chunkName = tempFileName;
                                if ( chunk != null )
                                {
                                    chunkName = chunk + "_" + tempFileName;
                                }
                                File savedFile = new File( uploadPath, chunkName );
                                item.write( savedFile );
                            }
                        }
                    }
    
                    // UUID+'.'+后缀名
                    newFileName = UUID.randomUUID().toString().replace( "-", "" )
                            .concat( "." )
                            .concat( FilenameUtils.getExtension( tempFileName ) );
                    if ( chunk != null && chunk + 1 == chunks )
                    {
                        outputStream = new BufferedOutputStream(
                                new FileOutputStream( new File( uploadPath, newFileName ) ) );
                        /* 遍历文件合并 */
                        for ( int i = 0; i < chunks; i++ )
                        {
                            File tempFile = new File( uploadPath, i + "_" + tempFileName );
                            byte[] bytes = FileUtils.readFileToByteArray( tempFile );
                            outputStream.write( bytes );
                            outputStream.flush();
                            tempFile.delete();
                        }
                        outputStream.flush();
                    }
                    Map<String, Object> m = new HashMap<String, Object>();
                    m.put( "status", true );
                    m.put( "fileUrl", bundle.getString( "uploadPath" ) + "/"
                            + newFileName );
                    response.getWriter().write( JSON.toJSONString( m ) );
                } catch ( FileUploadException e ) {
                    e.printStackTrace();
                    Map<String, Object> m = new HashMap<String, Object>();
                    m.put( "status", false );
                    response.getWriter().write( JSON.toJSONString( m ) );
                } catch ( Exception e ) {
                    e.printStackTrace();
                    Map<String, Object> m = new HashMap<String, Object>();
                    m.put( "status", false );
                    response.getWriter().write( JSON.toJSONString( m ) );
                } finally {
                    try {
                        if ( outputStream != null )
                            outputStream.close();
                    } catch ( IOException e ) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.getRequestDispatcher("/WEB-INF/views/student/uploadFile.jsp").forward(request, response);
        }
    }
    servlet

      注意:

    > request.getServletContext().getRealPath(virtualPath);  将虚拟路径转化成物理路径。
    > ResourceBundle bundle = ResourceBundle.getBundle( "config" );
    读取src下的config.properties文件。例如:file.config对应的文件为file包下config.properties文件
  • 相关阅读:
    咖啡里的梦
    杨元庆精彩演讲
    鲍尔默演讲
    买房子的涉及到的一些费用说明
    未来是通胀的十年
    百名经济学家企业家88%认为当前通胀情况严重
    给陌生人写一封信
    晌午时的休憩
    34个实用确很多人不知道的偏方
    思念
  • 原文地址:https://www.cnblogs.com/zhuxiang1633/p/8182118.html
Copyright © 2011-2022 走看看