2016-11-23 75 views
-2

路徑值返回根網站路徑。但是,我不想在那裏存儲圖像,我想從用戶那裏獲取圖像(當他們從本地上傳時)。需要上傳文件路徑才能轉換爲Byte []

我可以用我的本地路徑硬編碼字符串,它會工作,但不會在其他環境中工作。我正在運行.net核心1.0。

控制器:

foreach (var file in files) 
      { 
       if (file.Length > 0) 
       { 
        string path = Path.GetFullPath(model.Filename); 

        var img = Image.FromFile(Path.Combine(path, file.FileName)); 
        using (var ms = new MemoryStream()) 
        { 
         img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
         model.FileData = ms.ToArray(); 
        } 

       } 
      } 

查看:

<input asp-for="Filename" type="text" id="upload-banner" class="form-control" placeholder="Upload Image" readonly> 
<span class="input-group-btn"> 
<input id="i_file" type="file" name="files" multiple /> 
<button type="button" class="btn btn-effect-ripple btn-primary">Upload</button> 
</span> 

回答

1

你似乎是困惑如何上傳文件工程。後端代碼無權訪問提供文件的文件系統;相反,它來自HTTP管道。後端代碼必須接受該文件並將其保存在本地某個位置,然後才能在本地文件系統上使用它。

這樣的代碼可能工作:

[HttpPost] 
public ActionResult Index(HttpPostedFileBase file) 
{ 
    if (file.ContentLength > 0) 
    { 
     var fileName = Path.GetFileName(file.FileName); 
     var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
     file.SaveAs(path); 
    } 
    return RedirectToAction("Index"); 
} 

See this link一個完整的例子。

+0

謝謝,對不起,我沒有正確解釋自己,英語不是我的母語。在審查了這個之後,我得到了它的工作,問題是網核已經改變了很多mvc元素。感謝您的迴應。 –