使用jQuery和ASP.Net Handler同时上载多个文件上载控件上的文件

时间:2017-04-04 11:12:01

标签: c# jquery asp.net

我有一个包含多个文件上传控件的表单和一个用于在块中上传文件的处理程序。这适用于一次上传上传控件上的单个文件。但是我希望在块上传的同时在多个上传控件上传文件。请建议。



$(inputUploadElem).fileupload({
    url: '../Handler.ashx?upload=start',
    maxChunkSize: 10000000,
    //  fileInput: $(this).prop("files"),
    sequentialUploads: true,

    dropZone: $(this),
    //singleFileUploads: false,
    //  limitMultiFileUploads: 1,


    add: function (e, data) {
        var uploadErrors = [];
        globalid = $(this).attr("id");
        var file = data.files[0];
        oldfname = file.name;
        var name = file.name;
        var fname = name.substring(0, name.lastIndexOf("."));
        var ext = name.substring(name.lastIndexOf("."));

        var dt = new Date();

        var month = dt.getMonth() + 1;
        var day = dt.getDate();

        
        var strTempImg = "_" + dt.getFullYear() + "_" + (month < 10 ? '0' : '') + month + "_" + (day < 10 ? '0' : '') + day + "-" + dt.getHours() + dt.getMinutes() + dt.getSeconds();

        filename = fname + strTempImg + ext;
        globalid = $(this).attr('id');
        pathToUpload = $(this).attr('path');
        PathByControl = '';
        if (uploadErrors.length > 0) {
           
            alert(uploadErrors.join("\n"));

        }
        else
            data.submit();

    },
    formData: function (data) {
        var arrFormData = [];
        arrFormData.push({ name: "file", value: filename });
        arrFormData.push({ name: "controlid", value: globalid });
        arrFormData.push({ name: "RootPath", value: pathToUpload });
        arrFormData.push({ name: "PathByControl", value: PathByControl });
        return arrFormData;
        
    },
    done: function (response, status) {
        PopulateData(globalid);
        $('.uploadprogress', "#UploadDiv_" + globalid.substring(globalid.indexOf('_') + 1, globalid.length)).css('visibility', 'hidden');
    },
    success: function (response, status) {
        if (!(response === undefined || response == null))
        {
            var repData = JSON.parse(response);
            //Sending conditional path for next chunk
            PathByControl = respData.PathByControl;
        }

    },
    error: function (error) {      
        $('.uploadprogress', "#UploadDiv_" + globalid.substring(globalid.indexOf('_') + 1, globalid.length)).css('visibility', 'hidden');
        alert("An error has occurred during processing your request.");
    },
    chunksend: function (e, data) {
        
    },
    progress: function (e, data) {
        // Track Progress
        var progress = parseInt(data.loaded / data.total * 100, 10);
        
        $('.uploadprogress', "#UploadDiv_" + globalid.substring(globalid.indexOf('_') + 1, globalid.length)).css('display', '');
        $('.uploadprogress', "#UploadDiv_" + globalid.substring(globalid.indexOf('_') + 1, globalid.length)).css('visibility', 'visible');
        $('.uploadprogress', "#UploadDiv_" + globalid.substring(globalid.indexOf('_') + 1, globalid.length)).css('width', progress + '%');
        
    }
});
&#13;
&#13;
&#13;

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Configuration;
using System.Net;
using System.IO;

public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
    System.Collections.Specialized.NameValueCollection headers = context.Request.Headers;

    string rootPath = string.Empty,nodifiedFileName=String.Empty,controlId=String.Empty,pathByControl=String.Empty;
    if (context.Request.Form.Count >0 )
    {
        nodifiedFileName = context.Request.Form["file"];
        controlId = context.Request.Form["controlid"];
        rootPath = context.Request.Form["RootPath"];
        pathByControl = context.Request.Form["PathByControl"];
    }


    HttpRequest Request = context.Request;

    long chunks = 0;
    long chunk = 0;
    var Range = headers["Content-Range"];
    string startPosition = String.Empty;
    if (Range != null)
    {
        string[] arr = Range.ToString().Split('/');
        chunks = Convert.ToInt64(arr[1]) - 1;
        chunk = Convert.ToInt64(arr[0].Split('-')[1]);
        startPosition = arr[0].Split('-')[0].Trim();
    }

    HttpFileCollection SelectedFiles = context.Request.Files;

    try
    {

        HttpFileCollection files = Request.Files;
        HttpPostedFile postedFile = files[0];

        string filename = postedFile.FileName;
        HttpPostedFile PostedFile = SelectedFiles[0];
        string strFileName = Request.Form[0];

        Stream sreader = postedFile.InputStream;
        long length = postedFile.InputStream.Length;
        byte[] bytes = new byte[length];
        int bytetoread = sreader.Read(bytes, 0, bytes.Length);
        byte[] buffer = bytes;

        if (startPosition.Equals("bytes 0") || String.IsNullOrEmpty(startPosition))
        {
            // If first chunk the get conditional path from DB by control id
            pathByControl = GetPathFromDBByControlId(controlId);
        }
        if (chunk != chunks)
        {
            //Returning conditionl path for remain chunk
            context.Response.Write("{\"PathByControl\":\"" + pathByControl + "\"}");
        }

        // Uploading file on FTP server
        UploadFileOnFTP(strFileName, rootPath + pathByControl + nodifiedFileName, buffer, chunk, chunks); 

        if (chunk == chunks)
        {
            //If all chunks are uploaded then insert detail in DB
            InsertFileDetailInDB(rootPath + pathByControl + nodifiedFileName, nodifiedFileName, PostedFile.FileName);
        }
    }
    catch (Exception ex)
    {
        context.Response.Clear();
        context.Response.Write("{\"Error\":\"" + ex.Message+"\"}");
        GC.Collect();
    }
}
public bool IsReusable
{
    get
    {
        return false;
    }
}
public string GetPathFromDBByControlId(String ControlId)
{
    return "";
}
public void UploadFileOnFTP(string _FileName, string _UploadPath, byte[] bufferToWrite, long chunk, long chunks)
{
    string ftphost = ConfigurationManager.AppSettings["FTP_IP"].ToString();
    string ftpfullpath = "ftp://" + ftphost + "/" + _UploadPath;
    string _FTPUser = Convert.ToString(ConfigurationManager.AppSettings["FTP_USER"]);
    string _FTPPass = Convert.ToString(ConfigurationManager.AppSettings["FTP_PASS"]);

    try
    {
        System.Net.FtpWebRequest _FtpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(ftpfullpath));
        // Provide the WebPermission Credintials
        _FtpWebRequest.Credentials = new System.Net.NetworkCredential(_FTPUser, _FTPPass);
        // By default KeepAlive is true, where the control connection is not closed
        // after a command is executed.
        _FtpWebRequest.KeepAlive = true;
        // set timeout for 20 seconds
        _FtpWebRequest.Timeout = -1;
        // Specify the command to be executed.
        _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.AppendFile;
        // Specify the data transfer type.
        _FtpWebRequest.UseBinary = true;           
        using (Stream _Stream = _FtpWebRequest.GetRequestStream())
        {
            // System.IO.Stream _Stream = _FtpWebRequest.GetRequestStream();
            _Stream.Write(bufferToWrite, 0, bufferToWrite.Length);
            // Close the file stream and the Request Stream
            _Stream.Close();
            _Stream.Dispose();
            GC.Collect();

        }

    }
    catch (Exception ex)
    {
        throw ex;
    }
}
public void InsertFileDetailInDB(String Path, String ModifiedName, String OrigionalName)
{
}

}

0 个答案:

没有答案