繁体   English   中英

MVC-从Azure httppost返回CSHTML中的文件属性

[英]MVC - Returning File Attributes in CSHTML from Azure httppost

我遇到一个问题,即使变量名称存在于Controller中,我也无法返回正在上传到网站并存储在Azure上的文件的文件名和文件大小。

我的CSHTML的片段如下所示:

<table class="table table-striped table-hover ">  
<thead>
<tr>
    <th>FIlename</th>
    <th>Modified</th>
    <th>File Size</th>
    <th>Download File</th>
    <th>Delete File</th>
    </tr>
</thead>

<tbody>
@foreach (var item in Model)
{
<tr>
    <td>@item.Name</td>
    <td>Modified</td>
    <td>@item.ContentLength</td>
    <td><a id="@item" href="@item" onclick="downloadFile('@item')">Download</a></td>
    <td><a id="@item" href="#" onclick="deleteFile('@item')">Delete</a></td>
</tr>
}
</tbody>
</table>

如您所见,我有item.Name,但我尝试了许多其他方法,下面将对这些方法进行总结。 值得注意的是,我能够很好地下载和删除文件。

我的控制器最重要的部分是:

public class HomeController : Controller
{

    BlobStorageService _blobStorageService = new BlobStorageService();

    public ActionResult Upload()
    {
        CloudBlobContainer blobContainer = _blobStorageService.GetCloudBlobContainer();
        List<string> blobs = new List<string>();
        foreach (var blobItem in blobContainer.ListBlobs())
        {
            blobs.Add(blobItem.Uri.ToString());
        }
        return View(blobs);
    }

    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {
        if (file.ContentLength > 0)
        {
            CloudBlobContainer blobContainer = _blobStorageService.GetCloudBlobContainer();
            CloudBlockBlob blob = blobContainer.GetBlockBlobReference(file.FileName);
            blob.UploadFromStream(file.InputStream);
        }
        return RedirectToAction("Upload");
    }

如您所见,HomeController上下文中存在ContentLength,即文件大小和FileName。

为了使它正常工作,我尝试了以下不同的示例

@ item.FileName,@ item.file.FileName,@ item.HttpPostedFileBase.Filename @ file.FileName,@ item.filename-其他都相同。

如果您确实知道答案,能否告诉我找到答案的来源,我曾经使用过Python,这些Python都有其模块的文档,但这有很大的不同

问题在于用于呈现GET Upload视图的ViewModel。

[HttpGet]
public ActionResult Upload() {      
    List<string> blobs = new List<string>();
    // add URI strings to list ...
    return View(blobs, "Upload");
}

这意味着在您的CSHTML中, ModelList<string>

您真正想要的是一个视图模型集合,这些视图模型包含FileName和ContentLength,而不仅仅是URI。

public class FileDisplayModel {
    public string Uri { get; set; }
    public string Name { get; set; }
    public int ContentLength { get; set; }
}

@model中使用@model指令可让IDE检查是否从控制器传递了正确的模型。

@* Upload.cshtml *@
@model IList<FileDisplayModel>

可以在MSDN上找到.net的文档: HttpPostedFileBase类

这是我用于图像上传的教程: 具有视图模型的ASP.NET MVC中的文件上传

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM