我试图检查文件是否在mvc中的fileupload中使用Form集合选中但formvalues始终为null,fileupload没有将上传的文件名传递给formcollection,下面是代码:
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>
答案 0 :(得分:4)
您使用的是错误的ID(html中的“files1”和“files2”,但是 代码中的“file1”和“file2”
即使您使用了正确的ID, 此代码不起作用,因为表单参数使用命名 “name”属性中的值。因此,您必须创建一个唯一的名称 对于html中的每个输入标记,然后在代码中使用这些名称。
如果您想循环文件。您可以为它们提供相同的ID,然后在服务器端的控制器方法中使用Request.Files
属性。
答案 1 :(得分:0)
我目前用于通过多部分表单处理来自用户的文件加载的是以下代码。
对我来说,最棘手的事实是,我没有Models,而是拥有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>
从那里开始,表单由控制器处理(借助私有方法),如下面的代码所示。 (还为简洁和相关性进行了编辑)
public ActionResult ShipMethod(FormCollection fc)
{
// Gets the file(s) uploaded by the user using the form
HttpFileCollectionBase file = Request.Files;
// In this point I'm only looking for 1 file as that is all the user is allowed to upload
if (file.Count == 1)
{
// This being the reference to the private method mentioned earlier
/* We're passing the customer's cart and
* the file variable that was filled above as the Cart will be constant
* until the user confirms their purchase, making it ideal to hold on to
* the file details until the purchase is actually processed in the
* last step of the check out process. */
GetPO(_cart, file);
}
}
下面是实际处理上传文件的方法的代码。
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一起使用。
这是我们提供的解决方案,允许公司客户在从网站订购时上传采购订单。如果您想循环浏览文件,可以返回到第二个代码blurb,并在检查完文件后,可以循环浏览以进行处理。
这是通过ASP,MVC 4,.NET Framework 4.6.1完成的