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.

    评论

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的