0

我正在 asp mvc 中进行上传,第一次用户尝试将文件附加到模型中效果很好,文件是 system.web.httpfilewrapper 。

但是当涉及到第二次尝试时,控制器从其他文本框中捕获了无效数量,并且它回发给用户说无效,然后用户输入有效数量,然后它返回到控制器,这里开始让我有不知道发生了什么,文件突然变为空,它无法完成将值发布到模型中的以下代码行。

if (model.File != null && model.File.ContentLength > 0)
{
    Byte[] destination = new Byte[model.File.ContentLength];
    model.File.InputStream.Position = 0;
    model.File.InputStream.Read(destination, 0, model.File.ContentLength);
    model.BankSlip = destination;
}

毕竟我决定使用另一种方法来完成它,因为model.file是=null,所以我在第一个块中添加了一些代码让文件保存到App_Data中以供临时使用并稍后检索......

if (model.File != null && model.File.ContentLength > 0)
{
    Byte[] destination2 = new Byte[model.File.ContentLength];
    model.File.InputStream.Position = 0;
    model.File.InputStream.Read(destination2, 0, model.File.ContentLength);
    model.BankSlip = destination2;
    string chg = model.File.ToString();
    string file = Path.GetFileName(chg);
    string NewName = chg.Replace(file, member.MemberCode+".jpg");
    var fileName = Path.GetFileName(NewName);
    var savepath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
    model.File.SaveAs(savepath);

}

直到此时它工作正常,但问题开始于 else 块,我使用文件流读回文件并尝试将其定位回模型,一切正常,除了文件仍然 = Null。这是我问的一个愚蠢的问题,我不知道如何分配或将系统 io 转换为 httppostedfilebase,它一直向我显示被注释掉的错误,任何专业人士可以帮助我的愚蠢想法吗?我知道要解决这个问题,我实际上可以使用会话,但出于某种原因,我不想使用它,而是使用更长的方法来解决这个问题,如果有人能解决这个问题,我将不胜感激。

else
{
       FileStream fileStream = new FileStream(Path.Combine(Server.MapPath("~/App_Data"), member.MemberCode + ".jpg"), FileMode.Open, FileAccess.Read);
       int read = (int)fileStream.Length;
      // HttpPostedFileBase colbase = new HttpPostedFileWrapper();
       //model.File = colbase;
       Byte[] destination = new Byte[read];
       fileStream.Position = 0;
       fileStream.Read(destination, 0, read);
       model.BankSlip = destination;
}
4

1 回答 1

1

由于 httppostedfilebase 仅接受来自视图本身的值,因此它不起作用,否则它将从物理文件中获取任何内容。:)

仍然欢迎您回答这个问题。因为我发现这是 httppostedfilebase 的限制。

于 2014-10-01T10:14:14.127 回答