【问题标题】:Adding file to the database将文件添加到数据库
【发布时间】:2014-07-14 13:28:09
【问题描述】:

我正在尝试将文件添加到我的数据库中,但由于某种原因它无法正常工作,有人可以告诉我为什么。这是我的沙发:

        $(document).on("click", "#BUTTON", function () {
        var FILE= $('#name').val();

        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "@Url.Action("File", "Controller")",
            data: JSON.stringify(FILE),
        contentType: "application/json; charset=utf-8",
        success: function () {

        }
    });
    });

这是在我的控制器中发生的:

public ActionResult File(HttpPostedFileBase file)
    {
        if (file != null)
        {
            string pic = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(Server.MapPath("~/path"), pic);
            // file is uploaded
            file.SaveAs(path);

            // save the image path path to the database or you can send image 
            // directly to database
            // in-case if you want to store byte[] ie. for DB
            using (MemoryStream ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);
                byte[] array = ms.GetBuffer();
            }

        }
        // after successfully uploading redirect the user
        return Index();
    }
}

当我在HttpPostedFileBase file 行中放置一个刹车点时,文件有空值,我不知道为什么?如果我这样做alert(FILE);,那么我将获得完整的文件路径,例如G:/filename/imagename.jpg 但在控制器中路径没有被传递?

【问题讨论】:

  • .val() 只返回文件的字符串名称。 @Steven,不是真的,有ajax方法可以上传
  • @Steven 您可以使用 ajax 上传文件。也许在旧的浏览器中它不起作用,但新的浏览器可以。

标签: c# jquery


【解决方案1】:

如果您将使用文件收集您的输入,您可以这样做,所以试试吧。我希望它会有所帮助

$(document).on("click", "#BUTTON", function(){

//Create form data
var data = new FormData(); 

//attach your file
data.append('file', document.getElementById("fileHere").files[0]); 

//and send it on server
$.ajax({
    url: "@Url.Action("File", "Controller")",
    data: data,
    cache: false,
    contentType: 'multipart/form-data',
    processData: false,
    type: 'POST',
    success: function(data){
            }
        });
    });

【讨论】:

  • 当我运行代码时,我收到错误消息JavaScript runtime error: Unable to get property 'files' of undefined or null reference。在这一行 `data.append('file', document.getElementById("#name").files[0]); `
  • getElementById() 使用 DOM 而不是 Jquery 选择器。所以删除 # 并像这样输入 id document.getElementById("name")
【解决方案2】:

您将无法以这种方式发布文件,您唯一要做的就是发布文本值,在这种情况下是文件名。

也许这可以帮助你 (another example on stack overflow)

【讨论】:

    猜你喜欢
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多