异步上传文件(jquery.form)+进度条+上传到ftp服务器

Posted vinkong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异步上传文件(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;
    width: 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;
    width: 200px;
    height: 10px;
}
.progress {
    width: 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;
    width: 100%;
    height: auto;
}
.upload-file-stateWrap .progress {
    width: 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="width: 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,这个怎么配置,我也是百度的,自己可以尝试一下。

  

以上是关于异步上传文件(jquery.form)+进度条+上传到ftp服务器的主要内容,如果未能解决你的问题,请参考以下文章

异步上传文件,jquery+ajax,显示进度条

PHP+Ajax异步带进度条上传文件

PHP+ajaxForm异步带进度条上传文件实例

struts1 & jquery form 文件异步上传

struts1 & jquery form 文件异步上传

异步上传,显示进度条