Ajax多个文件上传,多个文件无法上传

时间:2013-01-11 11:06:11

标签: c# asp.net

我正在使用Ajax文件上传器,它可以将多个文件上传到数据库。但我面临一些问题。当我使用任何母版页时,只会上传多个所选文件中的1个文件,并且不会上传所有剩余文件。

但是当我不使用任何母版页时,它的工作正常。

我不确定此处提供的代码,请告诉我应提供哪些代码(CS或ASPX)以供参考。

cs code:

protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        try
        {       

        string path = Server.MapPath("~/Uploads/") + e.FileName;
        string ext = e.FileName.Split('.')[1];
        AjaxFileUpload1.SaveAs(path);
        string content_type="";
        object readOnly = false;

        object missing = System.Reflection.Missing.Value;
        //WdProtectionType typ = WdProtectionType.wdNoProtection;
        Word.Application app = new Word.Application();


            if ((ext == "doc") || (ext == "docx") || (ext == "DOC") || (ext == "DOCX"))
            {
                content_type = "application/vnd.ms-word";


                //Word.Document tempDoc = app.Documents.Open(path);
                //// tempDoc.TrackRevisions = true;
                ////  tempDoc.Protect(typ, ref missing, ref password, ref missing, ref missing);
                //tempDoc.Close(ref Nothing, ref format, ref Nothing);
            }

            if ((ext == "xlsx") || (ext == "xls") || (ext == "XLSX") || (ext == "XLS"))
            {
                content_type = "application/vnd.ms-excel";
                //Excel.Application ex_APP = new Excel.Application();
                //Excel.Workbook book = ex_APP.Workbooks.Open(path);
                //// book.KeepChangeHistory = true;
                //// book.HighlightChangesOnScreen = true;
                //book.Close(Nothing, path, Nothing);
            }

            if ((ext == "pdf") || (ext == "PDF"))
            {
                content_type = "application/pdf";
            }

            if ((ext == "txt") || (ext == "TXT"))
            {
                content_type = "text/plain";
            }


            if ((ext == "jpg") || (ext == "jpeg") || (ext == "JPG") || (ext == "JPEG"))
            {
                content_type = "image/jpeg";
            }


            byte[] imageBytes = File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/") + e.FileName);
            GENERIC.db.Document_Master_insert(e.FileName.ToString(), 1, imageBytes, "abcd_001", ext, System.DateTime.Now, "0.1", content_type);
            //BindGridviewData();
            File.Delete(Server.MapPath("~/Uploads/") + e.FileName);

        }
        catch (Exception ex)
        {

            throw;
        }


    }

aspx:

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
    <style>
        .modalBackground {
            background-color: Gray;
            filter: alpha(opacity=50);
            opacity: 0.50;
        }

        .pnl {
            background: #333;
            padding: 10px;
            border: 2px solid #ddd;
            float: left;
            font-size: 1.2em;
            color: White;
            position: fixed;
            top: 50%;
            left: 50%;
            z-index: 99999;
            box-shadow: 0px 0px 20px #999; /* CSS3 */
            -moz-box-shadow: 0px 0px 20px #999; /* Firefox */
            -webkit-box-shadow: 0px 0px 20px #999; /* Safari, Chrome */
            border-radius: 3px 3px 3px 3px;
            -moz-border-radius: 3px; /* Firefox */
            -webkit-border-radius: 3px; /* Safari, Chrome */
        }

        .close {
            DISPLAY: block;
            BACKGROUND: url(Images/close.png) no-repeat 0px 0px;
            LEFT: -12px;
            WIDTH: 26px;
            TEXT-INDENT: -1000em;
            POSITION: absolute;
            TOP: -12px;
            HEIGHT: 26px;
        }
    </style>
    <script type="text/javascript">
        function Success() {
            document.getElementById("lblMessage").innerHTML = "File Uploaded";

        }

        function Error() {
            document.getElementById("lblMessage").innerHTML = "Upload failed.";
        }
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">


    <div>
        <asp:GridView ID="gvDetails" CssClass="Gridview" runat="server" AutoGenerateColumns="false" DataKeyNames="CONTENT" OnSelectedIndexChanged="gvDetails_SelectedIndexChanged">
            <HeaderStyle BackColor="#df5015" />
            <Columns>

                <asp:TemplateField HeaderText="CODE">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkDownload" runat="server" Text='<% #Bind("CODE")%>' CommandName="Select"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>


                <%--<asp:BoundField DataField="CODE" HeaderText="CODE" />--%>
                <asp:BoundField DataField="Document_Name" HeaderText="Document_Name" />
                <%--<asp:TemplateField HeaderText="CONTENT">
                                <ItemTemplate>
                                    <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>--%>

                <asp:TemplateField HeaderText="PDF">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkPdf" runat="server" Text="View_Pdf" OnClick="lnkPdf_Click"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>


            </Columns>
        </asp:GridView>
    </div>
    <div>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="btnUpload" runat="server"
                    Text="Upload File" OnClick="btnUpload_Click" />
                &nbsp;&nbsp;&nbsp;

                    <%--<asp:Button ID="Open" runat="server"
                        Text="Open File" OnClick="get" />--%>



                <asp:ModalPopupExtender runat="server"
                    ID="modelPopupExtender1"
                    TargetControlID="btnUpload"
                    PopupControlID="popUpPanel"
                    OkControlID="btOK"
                    BackgroundCssClass="modalBackground">
                </asp:ModalPopupExtender>

                <asp:Panel ID="popUpPanel" runat="server" CssClass="pnl">
                    <div style="font-weight: bold; border: Solid 3px Aqua; background-color: AliceBlue">

                        <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
                            OnUploadComplete="UploadComplete"
                            OnClientUploadComplete="Success"
                            ThrobberID="loader" Width="400px" />
                        <asp:Image ID="loader" runat="server"
                            ImageUrl="~/loading.gif"
                            Style="display: None" />
                    </div>
                    <br />
                    <br />
                    <asp:Label ID="lblMessage" runat="server" /><br />
                    <br />
                    <asp:Button ID="btOK" runat="server" Text="OK" OnClick="btOK_Click" />
                    <asp:LinkButton ID="LinkButton1" runat="server" CssClass="close"
                        OnClientClick="$find('modelPopupExtender1').hide(); return false;" />
                </asp:Panel>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
</asp:Content>

1 个答案:

答案 0 :(得分:0)

在我的项目中,我这样做,我认为这会对你有所帮助。它在下面

首先添加以下参考文件

在aspx页面

    <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="js/jquery.uploadify.js"></script>


 <script type="text/javascript">
        $(function () {
            $("[id*=FileUpload1]").fileUpload({
                'uploader': 'js/uploader.swf',
                'cancelImg': 'images/cancel.png',
                'buttonText': 'Attach Files',
                'script': 'UploadFile.ashx',
                'folder': 'uploads',
                'multi': true,
                'auto': true,
                'onSelect': function (event, ID, file) {
                    $("#attachedfiles tr").each(function () {
                        if ($("td", this).eq(0).html() == file.name) {
                            alert(file.name + " already uploaded.");
                            $("[id*=FileUpload1]").fileUploadCancel(ID);
                            return;
                        }
                    });
                },
                'onComplete': function (event, ID, file, response, data) {
                    $("#attachedfiles").append("<tr><td>" + file.name + "</td><td><a href = 'javascript:;'>Cancel</a></td></tr>");
                }
            });
        });
        $("#attachedfiles a").live("click", function () {
            var row = $(this).closest("tr");
            var fileName = $("td", row).eq(0).html();
            $.ajax({
                type: "POST",
                url: "SendEmail.aspx/RemoveFile",
                data: '{fileName: "' + fileName + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () { },
                failure: function (response) {
                    alert(response.d);
                }
            });
            row.remove();
        });   
    </script>

然后我创建一个处理程序。此代码将帮助您上传恶意文件

public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;

        try
        {
            HttpPostedFile postedFile = context.Request.Files["Filedata"];

            string savepath = "";
            string tempPath = "";
            tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
            savepath = context.Server.MapPath(tempPath);
            string filename = postedFile.FileName;
            if (!Directory.Exists(savepath))
                Directory.CreateDirectory(savepath);
            postedFile.SaveAs(savepath + @"\" + filename);
            context.Response.Write(tempPath + "/" + filename);
            context.Response.StatusCode = 200;
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
        }
    }
相关问题