我正在从前端Angular 6向我的后端C#(ASP.NET)发送文件,并希望将该文件保存在后端服务器的文件夹中,并将该路径保存在MS SQL数据库中。
[EnableCors(origins: " * ", headers: " * ", methods: " * ")]
[AcceptVerbs("GET", "POST")]
[HttpGet]
[Route("CustomerSignature/Upload")]
public virtual IHttpActionResult Upload(int value)
{
string imageName = null;
string statuscode = " - 1";
string message = "";
HttpResponseMessage response = Request.CreateResponse();
try
{
var httpRequest = HttpContext.Current.Request;
}
catch (SqlException sqlex)
{
statuscode = "- 1";
response.StatusCode = HttpStatusCode.NotFound;
response.Headers.Add("Error", sqlex.Message);
message = ERPMessages.GetMessage(MessageType.FindByErrorSQL, this.Controller);
}
catch (Exception ex)
{
statuscode = " - 2";
response.StatusCode = HttpStatusCode.NotFound;
response.Headers.Add("Error", ex.Message);
message = ERPMessages.GetMessage(MessageType.FindByErrorGenaral, this.Controller);
}
return new MergeResult(response, statuscode, message, 0);
}
}
在上面,阅读“ HttpContext.Current.Request”后,如何获取请求中的文件并将其保存在文件夹中,以及如何将文件路径保存在数据库中?请帮我解决这个问题。
答案 0 :(得分:1)
您可以尝试类似以下的内容:
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var filePathCollection = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
filePathCollection.Add(filePath);
}
/// Save FilePathcollection in SQL Server
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}