从表单发布文件中获取FileStream

时间:2015-10-20 10:17:04

标签: asp.net asp.net-mvc file-upload

我在视图页面上有一个控件。当用户选择文件并单击提交按钮时,这会调用ajax来上传服务器上的文件。不幸的是,我的服务器方法接受要上传的文件路径(如C:/Videos/1.mp4)。这在下面的代码中与string demoPath很有效,但我不确定当用户选择控件时如何获得类似的路径。由于安全原因,现代浏览器不允许暴露路径。怎么做到这一点?

    [HttpPost]
    public async Task<JsonResult> Upload(string lectureId, string filepath)
    {
        for (int i = 0; i < Request.Files.Count; i++)
        {
            //// This works great
            //string demoPath = "C:/Users/abchi/Desktop/BigBuckBunny.mp4";


            var file = Request.Files[i];
            var fileName = Path.GetFileName(file.FileName);
            //var path = Path.Combine(Server.MapPath("~/User/"), fileName);
            //file.SaveAs(path);

            //await RunUploader(demoPath);
            await RunUploader(get_path_from_posted_file_or_request);
        }

        return Json(new { error = false, message = "Video uploaded." });
    }


    public async Task RunUploader(string filePath)
    {
        // :::::::
        using (var fileStream = new FileStream(filePath, FileMode.Open))
        {
            // ::::
        }
        // ::::::
    }

2 个答案:

答案 0 :(得分:1)

我不确定这是预期的,因为我不太明白。

下载用户计算机的文件路径不能是 - https://stackoverflow.com/a/15201258/4599089

但是如果您想要访问服务器上的FileStream:

文件有InputStream,你可以使用它:

[HttpPost]
public async Task<JsonResult> Upload(string lectureId, string filepath)
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];
        var fileName = Path.GetFileName(file.FileName);

        var path = Path.Combine(Server.MapPath("~/User/"), fileName);
        var fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
        file.InputStream.CopyTo(fileStream);
        fileStream.Close();

        await RunUploader(path); //path or stream
    }

    return Json(new { error = false, message = "Video uploaded." });
}


public async Task RunUploader(string filePath)
{
    // :::::::
    using (var fileStream = new FileStream(filePath, FileMode.Open))
    {
        // ::::
    }
    // ::::::
}

答案 1 :(得分:1)

我让我的同伴开始对public async Task RunUploader(string filePath)参数进行必要的更改。所述代码是用于控制台应用程序的YouTube .NET示例的一部分。现在我们正在为web开发,在这种情况下我们无法通过完整的路径。所以他们做了以下更改:

[HttpPost]
public async Task<JsonResult> Upload(string lectureId)
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];
        Stream fileStream = file.InputStream;
        await Run(fileStream);
    }

    return Json(new { error = false, message = "Video uploaded." });
}

public async Task Run(Stream fileStream)
{
    // ::::::::::
    using (fileStream)
    {
        // ::::::
    }
    // ::::::::::
}

现在有了这个改变,一切都开始了。