How to display image after selecting path in FileUpload controller without clicking

后端 未结 1 550
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-04 13:47

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



        
1条回答
  •  一个人的身影
    2021-02-04 14:12

    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:

    
    <%----%>
    
    
    

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

    
        
        
    
    

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

    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.
    }
    

    0 讨论(0)
提交回复
热议问题