0

I have an image box and a Photo Upload control with a Save button. I need to upload an image into the Image Box.

When I click the Upload button, it should show the Image in the Image Box.

When I click the Save button, the path of the uploaded image should be saved in the database.

My issue is the photo gets uploaded, but only after I click the Upload button for the second time.

P.S. I use a Client side function for uploading the photo.

Following are my codes.

CLIENT SIDE FUNCTION FOR UPLOADING THE PHOTO

function ajaxPhotoUpload() {

        var FileFolder = $('#hdnPhotoFolder').val();
        var fileToUpload = getNameFromPath($('#uplPhoto').val());

        var filename = fileToUpload.substr(0, (fileToUpload.lastIndexOf('.')));
        alert(filename);
        if (checkFileExtension(fileToUpload)) {

            var flag = true;
            var counter = $('#hdnCountPhotos').val();

            if (filename != "" && filename != null && FileFolder != "0") {
                //Check duplicate file entry
                for (var i = 1; i <= counter; i++) {
                    var hdnPhotoId = "#hdnPhotoId_" + i;

                    if ($(hdnPhotoId).length > 0) {
                        var mFileName = "#Image1_" + i;

                        if ($(mFileName).html() == filename) {
                            flag = false;
                            break;
                        }

                    }
                }
                if (flag == true) {
                    $("#loading").ajaxStart(function () {
                        $(this).show();
                    }).ajaxComplete(function () {
                        $(this).hide();
                        return false;
                    });


                    $.ajaxFileUpload({
                        url: 'FileUpload.ashx?id=' + FileFolder + '&Mainfolder=Photos' + '&parentfolder=Student',
                        secureuri: false,
                        fileElementId: 'uplPhoto',
                        dataType: 'json',
                        success: function (data, status) {

                            if (typeof (data.error) != 'undefined') {
                                if (data.error != '') {
                                    alert(data.error);
                                } else {

                                    $('#hdnFullPhotoPath').val(data.upfile);
                                    $('#uplPhoto').val("");
                                    $('#<%= lblPhotoName.ClientID%>').text('Photo uploaded successfully')
                                }
                            }


                        },
                        error: function (data, status, e) {
                            alert(e);
                        }
                    });
                }

                else {
                    alert('The photo ' + filename + ' already exists');
                    return false;
                }
            }
        }
        else {
            alert('You can upload only jpg,jpeg,pdf,doc,docx,txt,zip,rar extensions files.');
        }
        return false;

    }

PHOTO UPLOAD CONTROL WITH SAVE BUTTON AND IMAGE BOX

<table>
        <tr>
            <td>
    <asp:Image ID="Image1" runat="server" Height="100px" Width="100px" ClientIDMode="Static" />
                <asp:FileUpload ID="uplPhoto" runat="server" ClientIDMode="Static"/>
                <asp:Label ID="lblPhotoName" runat="server" Text="" ForeColor ="Green" ClientIDMode="Static"></asp:Label>
<asp:Button id="btnSave" runat="server" Text="Upload Photograph" onClick="btnSave_Click"  OnClientClick="return ajaxPhotoUpload();"/>
           </td>
                </tr>
            </table>

SAVE BUTTON CLICK EVENT IN SERVER SIDE (to show the uploaded image in the image box)

Protected Sub btnSave_Click(sender As Object, e As EventArgs)
    Image1.ImageUrl = hdnFullPhotoPath.Value

End Sub
MusicLovingIndianGirl
  • 5,909
  • 9
  • 34
  • 65

3 Answers3

0

I’d recommend that you drop client side AJAX upload via JS and stick to standard way of uploading. You can probably achieve the same effects without the excessive javascript.

If file type filtering is an issue you can check this post for more details.

Getting extension of the file in FileUpload Control

In either way you have to make a postback so it doesn’t really matter if you upload from JS or the server side except that second method is less complex.

Adding update panel will make this more user friendly and you should be all done.

Community
  • 1
  • 1
0
<head runat="server">
<title>Index</title>
 <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/ajaxupload.js" type="text/javascript"></script>
</head>

<body>

<div>
    <input type="button" id="uploadFile" value="Upload File" />(jpg|jpeg|png|gif)
    <div id="uploadStatus" style="color: Red">
    </div>
</div>
<script type="text/javascript" language="javascript">

        new AjaxUpload('#uploadFile', {
            action: 'Handler1.ashx',
            name: 'upload',
            onComplete: function (file, response) {

                if (response == '0') {
                    $('#uploadStatus').html("File can not be upload.");
                }
                else {
                    $('#img').attr("src", "response.path");
                }

            },
            onSubmit: function (file, ext) {
                if (!(ext && /^(jpg|jpeg|png|gif)$/i.test(ext))) {
                    $('#uploadStatus').html("Invalid File Format..");
                    return false;
                }

                $('#uploadStatus').html("Uploading...");
            }

        });

</script>

Then create a handler for uploading image on server

public class Handler1 : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string a = "1";

        if (context.Request.Files != null && context.Request.Files.Count > 0)
        {
            if (context.Request.Files[0].ContentLength > 1000)
            {
                a = "0";
            }
        }
        else
        {
            a = "0";
        }

        context.Response.Write(a);

        context.Response.End();

    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
DK Chauhan
  • 194
  • 1
  • 11
0

All, thanks for your time and help.! The tilde(~) symbol was the issue - the file's path wasn't recognized. So I modified my code to replace it with empty space.

var orgpath = data.upfile;
var photopath = orgpath.replace('~/', '');
$('#<%= ImgFacultyPhoto.ClientID%>').attr('src', photopath);
MusicLovingIndianGirl
  • 5,909
  • 9
  • 34
  • 65