无法更新FormView中的图像

时间:2018-08-27 23:45:33

标签: c# asp.net sql-server image file-upload

我需要您的帮助。我已经编写了一个代码来更新FormView中的图像。一切正常。但是,当立即从计算机中任何其他位置上载图像时,我单击更新时会收到一条错误消息,提示:找不到文件“ C:\ Program Files \ IIS Express \ FariPassport.jpg”。     这是我的aspx页面:                        
                                                              

                        <tr style="align-content:center">
                            <%--<th>Passport:
                            </th>--%>
                            <td>
                                <asp:Image ID="imgPicture" runat="server" ImageUrl='<%# Eval("ID","ShowImage.ashx?ID={0}") %>' Width="128px" Height="128px" />
                        </tr>

                        </td>
                    </tr>
                    <tr>
                        <td align="center">
                            <asp:Button ID="Button1" runat="server" Text="Edit" CommandName="Edit" CssClass="btn-danger" Font-Size="Large" Height="30px" Width="82px" />
                            <%--<asp:LinkButton ID="lnkEdit" runat="server" CommandName="Edit" Text="Edit" CssClass="btn-link" />--%>
                        </td>
                        <%--<td align="center">
                            <asp:LinkButton ID="lnkDelete" runat="server" CommandName="Delete" Text="Delete"
                                OnClientClick="return confirm('Are you sure to delete it completely?');" />
                        </td>--%>
                        <%--<td align="center">
                            <asp:LinkButton ID="lnkNew" runat="server" CommandName="New" Text="New" />
                        </td>--%>
                    </tr>
                    </table>
                </ItemTemplate>
                <EditItemTemplate>
                    <table width="100%" bgcolor="#FFCC00">
                        <tr>
                            <th>&nbsp;</th>
                            <td>
                                <asp:FileUpload ID="fupEditImage" runat="server" />
                                <asp:CustomValidator ID="cmvImageType" runat="server" ControlToValidate="fupEditImage"
                                    ErrorMessage="File is invalid!" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
                            </td>
                        </tr>
                        <tr>
                            <td align="center">

                                <asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update" Text="Update" ForeColor="White" />
                            </td>
                            <td align="center">
                                <asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" Text="Cancel"
                                    CausesValidation="False" ForeColor="White" />
                            </td>
                        </tr>
                    </table>
                </EditItemTemplate>
                <EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
                <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
                <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
                <InsertItemTemplate>
                    <table width="100%">

                        <tr>
                            <th>Passport:
                            </th>
                            <td>
                                <asp:FileUpload ID="fupInsertImage" runat="server" />
                                <asp:CustomValidator ID="cmvImageType" runat="server" ControlToValidate="fupInsertImage"
                                    ErrorMessage="File is invalid!" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
                            </td>
                        </tr>
                        <tr>
                            <td align="center">
                                <asp:LinkButton ID="lnkInsert" runat="server" CommandName="Insert" Text="Insert" />
                            </td>
                            <td align="center">
                                <asp:LinkButton ID="lnkInsertCancel" runat="server" CommandName="Cancel" Text="Cancel"
                                    CausesValidation="False" />
                            </td>
                        </tr>
                    </table>
                </InsertItemTemplate>
                <PagerStyle HorizontalAlign="Center" ForeColor="#8C4510" />
                <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
            </asp:FormView>
            <asp:SqlDataSource ID="SqlDSPersonDetails" runat="server" ConnectionString="<%$ ConnectionStrings:NNPC-ChevronScholarshipConnectionString %>" SelectCommand="SELECT [ID], [PassportFileName], [PassportImageType], [Passport] FROM [Candidates] WHERE ([UserId] = @UserId)"
                DeleteCommand="DELETE FROM Candidates WHERE (ID = @ID)" InsertCommand="INSERT INTO tb_personInfo(PassportFileName, Passport, PassportImageType) VALUES (@PassportFileName, @Passport, @PassportImageType)"
                UpdateCommand="UPDATE Candidates SET PassportImageType = @PassportImageType, Passport = @Passport  WHERE (ID = @ID)" OnSelecting="SqlDSPersonDetails_Selecting">
                <DeleteParameters>
                    <asp:Parameter Name="ID" Type="Int32" />
                </DeleteParameters>
                <InsertParameters>
                    <asp:Parameter Name="PassportFileName" Type="String" />
                    <asp:Parameter Name="Passport" DbType="Binary" ConvertEmptyStringToNull="true" />
                    <asp:Parameter Name="PassportImageType" Type="String" ConvertEmptyStringToNull="true" />
                </InsertParameters>
                <SelectParameters>
                    <asp:Parameter Name="UserId" Type="Object" />
                </SelectParameters>

                <UpdateParameters>
                    <%--<asp:Parameter Name="PassportFileName" Type="String" />--%>
                    <asp:Parameter Name="PassportImageType" Type="String" ConvertEmptyStringToNull="true" />
                    <asp:Parameter Name="Passport" DbType="Binary" ConvertEmptyStringToNull="true" />
                    <asp:Parameter Name="ID" Type="Int32" />
                </UpdateParameters>

            </asp:SqlDataSource>

        </div>




Below is my line of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Web.Security;

public partial class ORMApp_PassportUpdate : System.Web.UI.Page
{
    // Static types of common images for checking.
    private static List<string> imgytpes = new List<string>()
        {
            ".BMP",".GIF",".JPG",".PNG"
        };

    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void SqlDSPersonDetails_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        // Get a reference to the currently logged on user
        MembershipUser currentUser = Membership.GetUser();

        // Determine the currently logged on user's UserId value

        Guid currentUserId = (Guid)currentUser.ProviderUserKey;

        // Assign the currently logged on user's UserId to the @UserId parameter

        e.Command.Parameters["@UserId"].Value = currentUserId;
    }



    protected void fvPersonDetails_ItemInserting(object sender, FormViewInsertEventArgs e)
    {

    }


    protected void fvPersonDetails_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    {
        CustomValidator cv = fvPersonDetails.FindControl("cmvImageType") as CustomValidator;

        cv.Validate();
        e.Cancel = !cv.IsValid;

        FileUpload fup = (FileUpload)fvPersonDetails.FindControl("fupEditImage");

        if (cv.IsValid && fup.PostedFile.FileName.Trim() != "")
        {
            e.NewValues["Passport"] = File.ReadAllBytes(fup.PostedFile.FileName);
            e.NewValues["PassportImageType"] = fup.PostedFile.ContentType;
        }
    }

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (args.Value != null && args.Value != "")
        {
            args.IsValid = imgytpes.IndexOf(System.IO.Path.GetExtension(args.Value).ToUpper()) >= 0;
        }
    }

    protected void fvPersonDetails_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
    {

    }

    protected void fvPersonDetails_ItemInserted(object sender, FormViewInsertedEventArgs e)
    {

    }


    protected void fvPersonDetails_ItemDeleted(object sender, FormViewDeletedEventArgs e)
    {

    }


    protected void fvPersonDetails_ItemDeleting(object sender, FormViewDeleteEventArgs e)
    {

    }

    protected void fvPersonDetails_ModeChanging(object sender, FormViewModeEventArgs e)



    }
}

1 个答案:

答案 0 :(得分:0)

此行尝试将where读取为Web服务器内的本地文件,但由于文件未存储在服务器的文件夹中或路径不存在,因此在某些文件中找不到该文件:

PostedFile

您可以从e.NewValues["Passport"] = File.ReadAllBytes(fup.PostedFile.FileName); 的{​​{1}}属性中读取上传的文件作为PostedFile.InputStream实例,并将其分配给字节数组(假设FileUpload是字节数组):

Stream

此外,您可以使用e.NewValues["Passport"]var stream = fup.PostedFile.InputStream; // creates the stream stream.Read(e.NewValues["Passport"], 0, stream.Length); 属性检查上传的文件,而不用检查文件名:

HasFile

如果您需要保存上传的文件,请先使用PostedFile.ContentLength,然后使用if (cv.IsValid && fup.HasFile && fup.PostedFile.ContentLength > 0) { var stream = fup.PostedFile.InputStream; // creates the stream stream.Read(e.NewValues["Passport"], 0, stream.Length); e.NewValues["PassportImageType"] = fup.PostedFile.ContentType; } 进行读取。

相关问题:

ASP.NET/VB.NET FileUpload Control