C# 文件上传:无法将值分配到文件中,是否继续向我输入空值?需要帮助吗,专业人士?
我在asp mvc中做一个上传,第一次用户尝试将一个文件附加到模型中时效果很好,文件是system.web.httpfilewrapper 但当第二次尝试时,控制器从其他文本框中捕获了一个无效的量,它发回给用户说无效,然后用户输入一个有效的量,它返回到控制器,这里开始让我不知道发生了什么,file get突然变为null,它无法完成将值发布到模型中的以下代码行C# 文件上传:无法将值分配到文件中,是否继续向我输入空值?需要帮助吗,专业人士?,c#,asp.net-mvc,file,implicit-conversion,httppostedfilebase,C#,Asp.net Mvc,File,Implicit Conversion,Httppostedfilebase,我在asp mvc中做一个上传,第一次用户尝试将一个文件附加到模型中时效果很好,文件是system.web.httpfilewrapper 但当第二次尝试时,控制器从其他文本框中捕获了一个无效的量,它发回给用户说无效,然后用户输入一个有效的量,它返回到控制器,这里开始让我不知道发生了什么,file get突然变为null,它无法完成将值发布到模型中的以下代码行 if (model.File != null && model.File.ContentLength > 0) {
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_数据中,用于临时并在以后检索
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块,我使用filestream将文件读回并尝试将其定位回模型,所有工作正常,除了文件仍然为空。这是我问的一个愚蠢的问题,我不知道如何将系统io分配或转换为httppostedfilebase,它不断向我显示一个被注释掉的错误,任何专业人士都能帮我这个愚蠢的想法吗?我知道要解决这个问题,我可以使用session,但出于某种原因,我不想使用session,而是使用更长的方法,如果有人能解决这个问题,我将不胜感激
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;
}
它将无法工作,因为httppostedfilebase只接受来自视图本身的值,否则它将从物理文件中获取任何内容。:) 欢迎你回答这个问题。因为我发现这是httppostedfilebase的限制