Question

I trying to upload image using AsyncFileUpload and button. Below is the code I use to do it. But it causing double upload not sure how to let it upload image only after clicking the btnUpload. Current problem is that once I browse the image I want in asyncfileupload control there will be a loading.gif showing it loading and I refresh the page without clicking the btnUpload the image already been upload into database. What I wanted to do was let the image upload ONLY after clicking on the btnUpload. Do help out on solving this problem. THANKS!

Markup Code:

<script type="text/javascript" language="javascript">
    function StartUpload(sender, args) {
        var filename = args.get_fileName();
        var path = args.get_path();
        if (filename != "") {
            // code to get File Extension..
            var arr1 = new Array;
            arr1 = filename.split("\\");
            var len = arr1.length;
            var img1 = arr1[len - 1];
            var filext = img1.substring(img1.lastIndexOf(".") + 1);


            // Checking Extension
            if (filext == "jpg" || filext == "JPG") {
                $get("<%=lblUpload.ClientID %>").innerHTML = "";
                $get("<%=btnUpload.ClientID %>").disabled = false;
                return true;
            }
            else {
                $get("<%=lblUpload.ClientID %>").innerHTML = "Only .jpg and .JPG image allowed.";
                $get("<%=btnUpload.ClientID %>").setAttribute('disabled', 'disabled');
                return false;
            }
        }
    }

<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" 
CompleteBackColor="Lime" UploaderStyle="Modern" 
ErrorBackColor="Red" ThrobberID="Throbber" 
OnUploadedComplete="btnUpload_Click" 
UploadingBackColor="#66CCFF"
OnClientUploadStarted="StartUpload"
align="center"/>

<br />
<br />

<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="image/indicator.gif" alt="loading" />
</asp:Label>

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

<br />
<br />

<asp:Label ID="lblUpload" runat="server" Text=""></asp:Label>

btnUpload Code:

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (AsyncFileUpload1.HasFile == true)
        {
            String nric = (String)Session["nric"];

            string filePath = AsyncFileUpload1.PostedFile.FileName;
            string filename = Path.GetFileName(filePath);
            string ext = Path.GetExtension(filename);

            string contenttype = String.Empty;

            switch (ext)
            {
                case ".jpg":
                    contenttype = "image/jpg";
                    break;

                case ".JPG":
                    contenttype = "image/jpg";
                    break;
            }
            if (contenttype != String.Empty)
            {
                System.Drawing.Image uploaded = System.Drawing.Image.FromStream(AsyncFileUpload1.PostedFile.InputStream);

                System.Drawing.Image newImage = new Bitmap(1024, 768);
                using (Graphics g = Graphics.FromImage(newImage))
                {
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(uploaded, 0, 0, 1024, 768);
                }

                byte[] results;
                using (MemoryStream ms = new MemoryStream())
                {
                    ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
                    EncoderParameters jpegParms = new EncoderParameters(1);
                    jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
                    newImage.Save(ms, codec, jpegParms);
                    results = ms.ToArray();

                }

                //insert the file into database
                string strQuery = "Update MemberAccount Set profilepicture = @Data Where nric = @Nric";
                SqlCommand cmd = new SqlCommand(strQuery);

                cmd.Parameters.Add("@Nric", SqlDbType.VarChar).Value = nric;

                cmd.Parameters.AddWithValue("@Data", results);

                InsertUpdateData(cmd);

                UpdatePanel2.Update();                    

                lblUpload.ForeColor = System.Drawing.Color.Green;
                lblUpload.Text = "Profile Picture Updated.";
            }
        }
    }
Était-ce utile?

La solution

i think just removing the line below would make it ok

OnUploadedComplete="btnUpload_Click"

just let me know if it worked...

Autres conseils

I don't think you're using the AyncFileUpload control in the manner it was intended. The control is designed to upload the file AFTER you select the file automatically. The more correct terminology for your 'Upload' button would be 'Save' as the file already exists on the server it just needs to be saved.

By calling OnUploadedComplete you are effectively calling the code to save the file. From here:

UploadedComplete - Fired on the server side when the file successfully uploaded

As aliCna suggested you should remove this call as it seems to be redundant.

If you only want the file to be uploaded after you click an Upload button you'll need to investigate other controls you might want to have a look at other upload controls (such as the AjaxFileUpload or the standard File Upload Control in ASP.net [though I'm not too sure how well that plays with Update Panels]).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top