我正在尝试不使用FormData将文件传递给我的aspnet项目,所有值都已发送,但文件本身已发送。因此,我可以if ($('#Prop').get(0).files.length === 0
检查其中是否有东西,但无法发送。后面的模型具有HttpPostedFileBase
属性,我正尝试通过:
$('#Prop').get(0).files
$('#Prop').val()
不工作!
如果使用的是MVC结构,则可以使用以下代码:
MVC razar语法提供了@@ Ajax.Beginform(),在这里您可以发送“ multipart / form-data”。
@using (Ajax.BeginForm("action", YourController, new { id= Model.Id }, new AjaxOptions {needed options }, new { enctype = "multipart/form-data" }))
{
<input type="file" id="fileid" name="filename" />
<input type="submit" value="Modify" />
}
您可以使用它来将文件发送到控制器鉴于函数UploadTemplate(){
var filename = $("#ProcessTemplateUpload").val();
var re = /\..+$/;
var ext = filename.match(re);
if (ext == '.xlsx' || ext == '.XLSX' || ext == '.xls' || ext == '.XLS') {
var data = new FormData();
var files = $("#ProcessTemplateUpload").get(0).files;
if (files.length > 0) {
data.append("HelpSection", files[0]);
$.ajax({
url: '@Url.Content("~/Process/UploadProcessTemplate")',
type: "Post",
dataType: "HTML",
processData: false,
data: data,
contentType: false,
beforeSend: function () { $("#divLoading").show(); },
success: function (result) {
debugger;
$("#divLoading").hide(); // clear before appending new list
alert(result);
},
error: function (xhr, status) {
alert("Uploading Failed Please Select Correct File"); // clear before appending new list
$("#Failedrecords").html();
$("#divLoading").hide();
}
});
}
} else {
alert("Invalid filename, please select another file");
return false;
}
}
并在控制器中访问文件var pic = System.Web.HttpContext.Current.Request.Files [“ HelpSection”];
HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
var fileName = System.IO.Path.GetFileName(filebase.FileName);
//var path = Path.Combine(Server.MapPath("~/App_Data/upload"), fileName);
string destination = Request.PhysicalApplicationPath + "UploadCCIRecovery\\" + fileName;
string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + destination + @";Extended Properties=""Excel 12.0 Xml;HDR=YES""";
OleDbConnection myData = new OleDbConnection(strConn);
try
{
FileInfo MyFile = new FileInfo(Request.PhysicalApplicationPath);
DirectoryInfo MyDirectory = new DirectoryInfo(Request.PhysicalApplicationPath + "UploadCCIRecovery\\");
if (MyDirectory.Exists)
{ }
else
{
System.IO.Directory.CreateDirectory(Request.PhysicalApplicationPath + "UploadCCIRecovery\\");
}
if (MyFile.Exists)
{
System.IO.File.Delete(destination);
filebase.SaveAs(destination);
}
else
{
filebase.SaveAs(destination);
}
}
这里是完整的示例,
<div class="item form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="logo"> Logo <span class="required">*</span> </label> <div class="col-md-6 col-sm-6 col-xs-12"> <input id="CouncilLogo" class=" col-md-12 col-xs-12" name="Logo" type="file" > </div> <div class="col-md-3 col-sm-3 col-xs-12"> </div> </div> <div class="ln_solid"></div> <div class="form-group"> <div class="col-md-6 col-md-offset-3"> <button id="BtnCancel" type="submit" class="btn btn-primary">Cancel</button> <button id="BtnSubmit" type="submit" class="btn btn-success">Submit</button> </div> </div>
<script>
$("#BtnSubmit").click(function () {
var files = $("#Logo").get(0).files; var data = new FormData(); if (files.length > 0) { data.append("file", files[0]); } $.ajax({ url: "../controllername/SaveImage", type: "Post", data: data, async: false, contentType: false, processData: false, success: function (ReturnValue) { if (ReturnValue == "Error") { alert('Error'); } else { alert('Success'); } }, error: function (err) { alert('Something Went Wrong'); }, });
});
</script>
控制器代码:-
public ActionResult Insert(HttpPostedFileBase file)
{
string Output = "";
string ImageName = "";
try { ImageName = WebImagePath + " Logo/" +
System.IO.Path.GetFileName(file.FileName); }
catch (Exception e) { }
if (Output == "")
{
try
{
string physicalPath =
Server.MapPath(ImageName);
file.SaveAs(physicalPath);
objData.CouncilLogo = ImageName;
db.ImageMaster.Add(objData);
db.SaveChanges();
Output ="Saved"
}
catch (Exception e)
{
Output="Error";
}
}
return this.Json(Output);
}