2015-10-20 75 views
2

我有一個控制查看頁面。當用戶選擇文件並點擊提交按鈕時,這會使ajax調用將文件上傳到服務器上。不幸的是我的服務器方法接受上傳的文件路徑(如C:/Videos/1.mp4)。這在以下代碼中很適合string demoPath,但我不確定如何在用戶選擇控件時獲得類似的路徑。由於安全原因,現代瀏覽器不允許公開路徑。如何實現這一目標?從窗體獲取FileStream發佈文件

[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)) 
     { 
      // :::: 
     } 
     // :::::: 
    } 

回答

1

我問我的同事在public async Task RunUploader(string filePath)參數做了必要的修改。該代碼是用於控制檯應用程序的YouTube .NET示例的一部分。現在我們正在爲網絡開發,在這種情況下,我們無法通過完整的路徑。所以他們做了如下改變:

[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) 
    { 
     // :::::: 
    } 
    // :::::::::: 
} 

現在有了這個改變一切開始工作。

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)) 
    { 
     // :::: 
    } 
    // :::::: 
} 
+0

謝謝Bartosz。好點,我已經解決了這個問題。 –