How to display image after selecting path in FileU

2019-03-15 16:29发布

问题:

Recently I have been developing web form application in ASP.NET (c#): I have an Image control:

<asp:Image ID="Avatar" runat="server" Height="225px" ImageUrl="~/Images/NoUser.jpg" Width="225px" />

And FileUpload & Button control

<asp:FileUpload ID="avatarUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />

When user click button then "Upload" code is executed (the image is sent to the database). Problem is that I like to display the image which the user selected in Avatar Image controller before the user clicks "desperate" button.

Is that possible to do this automatically?

回答1:

With the help of File Api of HTML5 (Example: Using files from web applications) you can accomplish this easily. Change the markup to use input type="file" instead of asp:FileUpload and add ID, add tag runat="server" to make it accessible from server. Your markup should look like:

<input ID="avatarUpload" type="file" name="file" onchange="previewFile()"  runat="server" />
<%--<asp:FileUpload ID="avatarUpload" runat="server" />--%>
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<asp:Image ID="Avatar" runat="server" Height="225px" ImageUrl="~/Images/NoUser.jpg" Width="225px" />

Now add a javascript function previewFile in the head of document:

<head runat="server">
    <title></title>
    <script type="text/javascript">
        function previewFile() {
            var preview = document.querySelector('#<%=Avatar.ClientID %>');
            var file = document.querySelector('#<%=avatarUpload.ClientID %>').files[0];
            var reader = new FileReader();

            reader.onloadend = function () {
                preview.src = reader.result;
            }

            if (file) {
                reader.readAsDataURL(file);
            } else {
                preview.src = "";
            }
        }
    </script>
</head>

Now after selecting an image you can see the preview like below:

You can use css to re-size it to a thumbnail. After clicking the Upload button, in the code you can find the posted file:

protected void Upload(object sender, EventArgs e)
{
    int contentLength = avatarUpload.PostedFile.ContentLength;//You may need it for validation
    string contentType = avatarUpload.PostedFile.ContentType;//You may need it for validation
    string fileName = avatarUpload.PostedFile.FileName;
    avatarUpload.PostedFile.SaveAs(@"c:\test.tmp");//Or code to save in the DataBase.
}