weixin_33701617 2017-02-28 17:10 采纳率: 0%
浏览 33

Ajax图片上传器问题

I have a issue with a image uploader i am making in ASP. I want to upload a image to the projects folder using ajax.

my html and js:

    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
    <a href="#" id="btnImg" onclick="uploadImg()" runat="server">UPLOAD</a>
    </div>
    </form>

<script>
    function uploadImg(){
        var formData = new FormData();
        formData.append('FileUpload1', $('#btnImg')[0].files[0]);
        $.ajax({
            type: "POST",
            url: 'Default.aspx/imageUpload',
            data: formData,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                alert(data);
            }
        });

    }
</script>

my image upload code(c#):

[WebMethod]
protected void imageUpload(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        Guid _fileNameRandom = Guid.NewGuid();
        string _fileNameStr = _fileNameRandom.ToString();
        FileUpload1.PostedFile.SaveAs(Server.MapPath("/Images/") + (_fileNameStr + fileName));
        Response.Redirect(Request.Url.AbsoluteUri);
    }
}

IN console i get the following errors: Uncaught TypeError: Cannot read property '0' of undefined at uploadImg (Default.aspx:32) at HTMLAnchorElement.onclick (Default.aspx:21)

line 32 in default.aspx is: }); of the js script. and line 21 is: function uploadImg(){

Hope anyone can help me resolve this.

  • 写回答

1条回答 默认 最新

  • weixin_33724046 2017-02-28 17:25
    关注

    $('#btnImg')[0] is the culprit.

    $('#btnImg')[0] will never have a files collection, because that's an anchor element, try changing it to $('#FileUpload1')[0], and see if that works? If not, you need to reference the input[type='file'] element which I think the ASP helper should render for you with that id.

    评论

报告相同问题?