最近寫了一個小項目需要上傳文件顯示進度條到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,這個怎么配置,我也是百度的,自己可以嘗試一下。