Asp.net mvc 从mvc中的FormCollection值获取Fileupload值
我正在尝试使用Form collection检查是否在mvc的fileupload中选择了该文件,但FormValue始终为空,fileupload没有将上载的文件名传递给formcollection,下面是代码:Asp.net mvc 从mvc中的FormCollection值获取Fileupload值,asp.net-mvc,asp.net-mvc-2,file-upload,Asp.net Mvc,Asp.net Mvc 2,File Upload,我正在尝试使用Form collection检查是否在mvc的fileupload中选择了该文件,但FormValue始终为空,fileupload没有将上载的文件名传递给formcollection,下面是代码: public ActionResult Create(FormCollection formValues,IEnumerable<HttpPostedFileBase> files, Venue venue) { string[] image
public ActionResult Create(FormCollection formValues,IEnumerable<HttpPostedFileBase> files, Venue venue)
{
string[] images = { "", "" };
int i = 0;
// string smallImage;
// string largeImage;
foreach (HttpPostedFileBase file in files)
{
if (file != null)
{
if (i == 0)
{
string newFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(file.FileName));
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/images/content/"), fileName);
file.SaveAs(path);
Helpers.ImageHelpers.ResizeImage(newFileName, path, "/Content/images/content/", 162, 105);
images[0] = newFileName;
venue.ImageSmall = images[0];
// smallImage = "selected";
}
if (i == 1)
{
string newFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(file.FileName));
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/images/content/"), fileName);
file.SaveAs(path);
Helpers.ImageHelpers.ResizeImage(newFileName, path, "/Content/images/content/", 212, 240);
images[1] = newFileName;
venue.ImageLarge = images[1];
// largeImage = "selected";
}
}
i++;
}
if (string.IsNullOrEmpty(formValues["files1"]) || string.IsNullOrEmpty(formValues["files2"]) )
{
ModelState.AddModelError("files", "Please upload a file");
}
<td>
<div class="editor-field">
<input type="file" name="files" id="files1" style="color:White" />
</div>
</td>
</tr>
<tr>
<td>
Detail Image
</td>
<td>
<div class="editor-field">
<input type="file" name="files" id="files2" style="color:White"/>
</div>
</td>
</tr>
public ActionResult创建(FormCollection FormValue、IEnumerable文件、场地)
{
字符串[]图像={“”“”};
int i=0;
//字符串图像;
//字符串大图像;
foreach(文件中的HttpPostedFileBase文件)
{
如果(文件!=null)
{
如果(i==0)
{
string newFileName=string.Format(“{0}{1}”,Guid.NewGuid().ToString(),Path.GetExtension(file.FileName));
var fileName=Path.GetFileName(file.fileName);
var path=path.Combine(Server.MapPath(“~/Content/images/Content/”),文件名);
file.SaveAs(路径);
Helpers.ImageHelpers.ResizeImage(新文件名,路径,“/Content/images/Content/”,162105);
图像[0]=新文件名;
vitune.ImageSmall=图像[0];
//smallImage=“选定”;
}
如果(i==1)
{
string newFileName=string.Format(“{0}{1}”,Guid.NewGuid().ToString(),Path.GetExtension(file.FileName));
var fileName=Path.GetFileName(file.fileName);
var path=path.Combine(Server.MapPath(“~/Content/images/Content/”),文件名);
file.SaveAs(路径);
Helpers.ImageHelpers.ResizeImage(新文件名,路径,“/Content/images/Content/”,212,240);
图像[1]=新文件名;
VICENUE.ImageLarge=图像[1];
//largeImage=“已选定”;
}
}
i++;
}
if(string.IsNullOrEmpty(formValues[“files1”])| | string.IsNullOrEmpty(formValues[“files2”]))
{
AddModelError(“文件”,“请上传文件”);
}
细节图像
如果你想循环文件。你可以给它们相同的id,然后在服务器端的控制器方法中使用
Request.files
属性。我当前使用的是以下代码来处理用户通过多部分表单加载的文件
对我来说最关键的是,我没有模型,我有一个BusinessLogicLayer.dll文件作为我的模型,除了我项目中的一个程序员遇到的一些罕见的异常
这部分是视图的形式,为了简洁起见删除了大量代码,只保留了与此问题相关的内容
<form id="payInfo" name="payInfo" action="@Url.Action("ShipMethod", "CheckOut")" method="post" enctype="multipart/form-data">
<div id="12" class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="payInvoice" name="payMethod" required />
<!--on submit if this is selected, the customer will see a thank you as well as instructions on when/how the invoice will be available.-->
<label class="custom-control-label" for="payInvoice">Send Invoice</label>
</div>
<div id="invoice" class="collapse img-thumbnail">
<p class="h6 mb-2">You can provide the PO number on your Purchase Order, or you can accept the generated PO number that we have provided for you.</p>
<div class="form-group row">
<label for="invoicePO" class="col-2 col-form-label font-weight-bold">po number: </label>
<div class="col-4"><!--Invoice name/prefill--></div>
<div class="col-6"> </div>
</div>
<div class="form-group row">
<label for="POfile" class="col-2 col-form-label font-weight-bold">PO PDF: </label>
<div class="col-4"><input type="file" class="form-control-file" id="POfile" name="POfile" /></div>
<div class="col-6"> </div>
</div>
</div>
<button class="btn btn-secondary btn-lg btn-block" type="submit">Continue To Shipping</button>
</form>
下面是实际处理上传文件的方法的代码
private void GetPO(Cart _cart, HttpFileCollectionBase file)
{
// Setting up a regEx to help me to restrict the kinds of files the user can upload to our server
string fileRegEx = @"^.+\.((pdf))$";
Regex regex = new Regex(fileRegEx, RegexOptions.IgnoreCase);
// This gets just the filename and its extension instead of the fully qualified name
// which we don't want when working with the RegEx comparison
string fileName = Path.GetFileName(file[0].FileName);
if (regex.IsMatch(fileName))
{
// If we're here, then the file name indicates that the file is a PDF
if (file != null && file[0].ContentLength > 0)
{
// If we're here then there is actual substance to the file that was uploaded
// So we'll need to make a byte array to temporarily
// hold the file contents before storage
byte[] upload = new byte[file[0].ContentLength];
// Get the File contents
file[0].InputStream.Read(upload, 0, file[0].ContentLength);
// Now that we have the contents, pass those contents on
// to the object that will hold onto it till the purchase
// is in the final stage of processing
_cart.POContent = upload;
// This section will get the other pertinent data pieces for storage
// Get the index of the last period in the file name
int lastIndex = fileName.LastIndexOf('.');
// Get the file extension
string ext = fileName.Substring(++lastIndex);
// Get the POName and POContentType
if (ext.ToLower() == "pdf")
{
// Get the Media Content Type
_cart.POContentType = MediaContentType.PDF;
// Get the name of the file without the extension
_cart.POName = fileName.Remove(--lastIndex);
}
else
{
// TODO: Error handling for the wrong file extension
}
}
}
else
{
// TODO: Set up Error Handling for invalid or empty file
}
}
这一轮代码还没有完全准备好供公众使用,但我知道这一点与我们的BLL和DAL结合起来确实有效
这是一个解决方案,允许公司客户在从网站订购时上传采购订单。如果您想循环浏览您的文件,可以返回到第二个代码栏,在检查您是否有文件后,可以循环浏览以进行处理
这是通过ASP、MVC 4、.NET Framework 4.6.1来完成的。很抱歉,这是一个打字错误,我无法更改名称,因为我正在传递文件IEnumerable files code updated…当我尝试将名称从文件更改为任何其他唯一名称时,foreach(文件中的HttpPostedFileBase文件)上会出现错误循环,对象引用未设置为对象的实例。请使用public ActionResult创建(FormCollection formValues、HttpPostedFileBase file1、HttpPostedFileBase file2、Venue-Venue)并在HtmlTill formValues[“file1”]中创建相同的2个名称,formValues[“file2”]为空。您不需要使用formValues数组。您必须使用Request.Files[0],Reuqest.Files[1]等。。
private void GetPO(Cart _cart, HttpFileCollectionBase file)
{
// Setting up a regEx to help me to restrict the kinds of files the user can upload to our server
string fileRegEx = @"^.+\.((pdf))$";
Regex regex = new Regex(fileRegEx, RegexOptions.IgnoreCase);
// This gets just the filename and its extension instead of the fully qualified name
// which we don't want when working with the RegEx comparison
string fileName = Path.GetFileName(file[0].FileName);
if (regex.IsMatch(fileName))
{
// If we're here, then the file name indicates that the file is a PDF
if (file != null && file[0].ContentLength > 0)
{
// If we're here then there is actual substance to the file that was uploaded
// So we'll need to make a byte array to temporarily
// hold the file contents before storage
byte[] upload = new byte[file[0].ContentLength];
// Get the File contents
file[0].InputStream.Read(upload, 0, file[0].ContentLength);
// Now that we have the contents, pass those contents on
// to the object that will hold onto it till the purchase
// is in the final stage of processing
_cart.POContent = upload;
// This section will get the other pertinent data pieces for storage
// Get the index of the last period in the file name
int lastIndex = fileName.LastIndexOf('.');
// Get the file extension
string ext = fileName.Substring(++lastIndex);
// Get the POName and POContentType
if (ext.ToLower() == "pdf")
{
// Get the Media Content Type
_cart.POContentType = MediaContentType.PDF;
// Get the name of the file without the extension
_cart.POName = fileName.Remove(--lastIndex);
}
else
{
// TODO: Error handling for the wrong file extension
}
}
}
else
{
// TODO: Set up Error Handling for invalid or empty file
}
}