zoukankan      html  css  js  c++  java
  • 异步上传文件(jquery.form)+进度条+上传到ftp服务器

    最近写了一个小项目需要上传文件显示进度条到ftp,总结一下分享

    我用的是jQuery.form.js上传

    ftp服务器,自己百度去搭建很简单的

    Talk is cheap.Show me your code.

            GitHub上面的源码:https://github.com/Vinkong/learngit

    aspx页面

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
       <script src="jquery-3.4.1.min.js"></script>
        <script src="jquery.form.js"></script>
     
        <style>
    
            .hidden{display:none;}
    .upload-fileWrap {
        margin: 3px 0 0 -2px;
        position: relative;
    }
    .upload-input-file {
        position: absolute;
        left: 2px;
        top: 0;
        display: inline-block;
         88px;
        height: 34px;
        line-height: 34px;
        opacity: 0;
        cursor: pointer;
        z-index: 2;
    }
    .upload-file-result {
        color: #a1acc6;
        font-size: 14px;
    }
    /*进度条*/
    .progressWrap {
        position: absolute;
        right: 20px;
        top: 56px;
         200px;
        height: 10px;
    }
    .progress {
         100%;
        height: 20px;
        background: #0f1529;
        -webkit-border-radius: 20px;
        -moz-border-radius: 20px;
        border-radius: 20px;
        overflow: hidden;
    }
    .progress-bar {
        height: 20px;
        background: url("blue.jpg") repeat-x;
    }
    .progress-bar span {
        position: absolute;
        color: #58637e;
        font-size: 12px;
        line-height: 18px;
    }
    .progress-bar span.progress-bar-status {
        left: 50%;
        top: -23px;
        margin-left: -15px;
        color: #1cc3b0;
    }
    .upload-file-stateWrap {
        position: relative;
         100%;
        height: auto;
    }
    .upload-file-stateWrap .progress {
         60%;
    }
    .upload-file-stateWrap span.progress-bar-status {
        top: inherit;
        bottom: -3px;
        left: 60%;
        margin-left: 5px;
    }
    
    
        </style>
        <script>
          
    
            function addfile() {
                var progress = $(".progress-bar"),
                status = $(".progress-bar-status"),
                percentVal = '0%';
                //上传步骤 
                var addvediofile = "";
                var filePath =$('#upload-input-file').val();
                var startIndex = filePath.lastIndexOf(".");
                if (startIndex != -1)
                    addvediofile = filePath.substring(startIndex + 1, filePath.length).toLowerCase();
                else
                    type = "";
                if (addvediofile != "mp4" && addvediofile != "rmvb" && addvediofile != "avi" && addvediofile != "ts") {
    
                    alert("文件格式不对");
                    $('#upload-input-file').val("");//介绍视频
                    return;
                }
    
                var size = 0;
                size = $("#upload-input-file")[0].files[0].size; //byte
                size = size / 1024;//kb
                size = (size / 1024).toFixed(3);//mb
                if (size > 100) {
    
                    alert("文件超过100M,无法上传");
                    return;
                }
                $("#myupload").ajaxSubmit({
                    url: './ashx/Handler.ashx',
                    type: "post",
                   beforeSend: function () {
                        $(".progress").removeClass("hidden");
                        progress.width(percentVal);
                        status.html(percentVal);
                         },
                    uploadProgress: function (event, position, total, percentComplete) {
                        percentVal = percentComplete + '%';
                        progress.width(percentVal);
                        status.html(percentVal);
                        console.log(percentVal, position, total);
                    },
                    success: function (result) {
                        //alert(result);
                        percentVal = '100%';
    
                        progress.width(percentVal);
                        status.html(percentVal);
                        ////获取上传文件信息 
                        alert("上传成功");
                        
                        //uploadFileResult.push(result);
                        //// console.log(uploadFileResult); 
                        $(".upload-file-result").html(result);
                        $("#upload-input-file").val('');
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log(errorThrown);
                        $(".upload-file-result").empty();
                    }
                });
          
    
    
    
    
            }
              
    
     
        </script>
    </head>
    <body>
       <div class="upload-fileWrap">
    
        <form id='myupload' name='myupload'  enctype='multipart/form-data'>
            <input id="upload-input-file" class="" name="file" type="file"  data-value-update="input"/>
       
            <input type="button" onclick="addfile();"  value="提交"/>
       
        </form>
        <div class="upload-file-stateWrap">
            <div style="margin-top:100px;">  <span class="upload-file-result"></span>            </div>
          
            <div class="progress hidden">
                <div class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" style=" 0%;">
                    <span class="progress-bar-status">0%</span>
                </div>
            </div>
        </div>
    </div>
    
    </body>
    </html>
    

      一般处理程序文件

     1 <%@ WebHandler Language="C#" Class="Handler" %>
     2 
     3 using System;
     4 using System.Web;
     5 using System.Collections.Generic;
     6 using System.IO;
     7 using System.Linq;
     8 using System.Net;
     9 using System.Web;
    10 public class Handler : IHttpHandler {
    11     
    12     public void ProcessRequest (HttpContext context) {
    13         context.Response.ContentType = "text/plain";
    14           
    15        string ftpUserID ="kfz";
    16        string ftpServerIP = "192.168.0.102";
    17        string ftpPassword ="kfz123456";
    18        string ftpRemotePath ="test";
    19 
    20       string   ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
    21         HttpFileCollection files = context.Request.Files;
    22 
    23         if (files.Count > 0)
    24         {
    25             HttpPostedFile fileInf = files[0];
    26             FtpWebRequest reqFTP;
    27             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.FileName));
    28             reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    29             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
    30             reqFTP.KeepAlive = false;
    31             reqFTP.UseBinary = true;
    32             reqFTP.ContentLength = fileInf.ContentLength;
    33             int buffLength = 2048;
    34             byte[] buff = new byte[buffLength];
    35             int contentLen;
    36             Stream fs = fileInf.InputStream;
    37             try
    38             {
    39                 Stream strm = reqFTP.GetRequestStream();
    40                 contentLen = fs.Read(buff, 0, buffLength);
    41                 while (contentLen != 0)
    42                 {
    43                     strm.Write(buff, 0, contentLen);
    44                     contentLen = fs.Read(buff, 0, buffLength);
    45                 }
    46                 strm.Close();
    47                 fs.Close();
    48                 context.Response.Write(fileInf.FileName);
    49             }
    50             catch (Exception ex)
    51             {
    52                 throw new Exception(ex.Message);
    53             }
    54         }
    55         
    56         
    57     }
    58  
    59     public bool IsReusable {
    60         get {
    61             return false;
    62         }
    63     }
    64 
    65 }

    说一下我遇到的一些问题,首先我遇到了一开始怎么都触发不了异步,无法进入一般处理程序,但是通过前端调试,可以看到触发了uploadProgress回调函数,最后发现是文件太大了,需要配置webconfig,可以根据自己的需求来配置

    <?xml version="1.0" encoding="utf-8"?>
    
    <!--
      有关如何配置 ASP.NET 应用程序的详细信息,请访问
      http://go.microsoft.com/fwlink/?LinkId=169433
      -->
    
    <configuration>
    
        <system.web>
          <compilation debug="true" targetFramework="4.5" />
       
        <httpRuntime requestValidationMode="2.0" maxRequestLength="2097151" executionTimeout="36000" />
        </system.web>
        <system.webServer>
            <security>
                <requestFiltering>
                    <requestLimits maxAllowedContentLength="102400000" />
                </requestFiltering>
            </security>
        </system.webServer>
    
    </configuration>
    

      如果你发布到iis中运行,也需要去iis管理器去配置编辑器中设置,默认只能上传30M,这个怎么配置,我也是百度的,自己可以尝试一下。

      

  • 相关阅读:
    YTU 2543: 数字整除
    YTU 2542: 弟弟的作业
    YTU 2541: 汽水瓶
    YTU 2535: C++复数运算符重载(+与<<)
    YTU 2530: 小勇玩lol
    YTU 2520: 小慧唱卡拉OK
    YTU 2517: 打倒魔王↖(^ω^)↗
    YTU 2516: 剪刀石头布
    reload、replace、href、assign、window.history.go(0)的区别
    js 数组排序sort方法
  • 原文地址:https://www.cnblogs.com/Vinkong/p/10865431.html
Copyright © 2011-2022 走看看