我想将图像上传到图像文件夹,但是会显示此错误。前面是Angular 7。
Asp.Net Core MVC
public bool AddCustomer(ExpressWebApi.Models.CustomerModel customer)
{
SqlConnection con =new SqlConnection();
con.ConnectionString="Data Source=.;Initial Catalog=BLAbLADB;Persist Security Info=True;User ID=sa;Password=sasasa";
SqlCommand cmd = new SqlCommand();
cmd.Connection=con;
//file upload start-----------------------
string imageName = null;
var httpRequest = HttpContext.Current.Request;
//upload the image
var postedFile = httpRequest.Files["cusImage"];
//Current custome filename
imageName = new string(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
postedFile.SaveAs(filePath);
//file upload end-------------------------
cmd.CommandText=$@"INSERT INTO Customer ([CusName], [CusPassword], [CusEmail], [CusDob], [CusImage]) VALUES ('{customer.CusName}', '{customer.CusPassword}', '{customer.CusEmail}', '{customer.CusDob}','{imageName}');";
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
return true;
}
var customerData = {
"cusName": form.value.userName,
"cusPassword": form.value.password,
"cusEmail": form.value.email,
"cusDob": form.value.dob,
"cusImage" : this.fileToUpload
};
//for photo upload start---------------------------------
handleFileInput(file:FileList){
this.fileToUpload=file.item(0);
//show image preview
var reader = new FileReader();
reader.onload=(event:any)=>{
this.imageUrl=event.target.result;
}
reader.readAsDataURL(this.fileToUpload);
}
//for photo upload end---------------------------------
错误CS0117'HttpContext'不包含'当前'的定义
答案 0 :(得分:1)
在.NET Core中,上下文是HttpContext
属性的一部分,是控制器类的一部分。并且该请求以HttpContext.Request
的形式提供,您可以从那里访问表单数据。
但是,在Core中,文件上传的语法已更改,因此,上面的代码如果不进行一些更改就无法正常工作。在您的情况下,您正在使用模型绑定,则需要设置请求模型来处理传入的文件。
以下内容来自ASP.NET Core docs上的Http Upload文档:
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePath});
}
您可以对模型中的单个文件或通过[FromBody]作为参数传递的单个文件使用相同的界面。
在您的情况下,您的传入模型应具有以下属性:
public IFormFile cusImage {get; set;}
捕获入站文件。