【发布时间】:2017-08-03 16:35:23
【问题描述】:
我有将图像写入文件夹的 WebAPI 方法。效果很好。
这是方法的代码
[Route("api/PostUserImage")]
[AllowAnonymous]
public async Task<HttpResponseMessage> PostUserImage()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 1 mb.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else
{
var date = DateTime.Now.ToString();
var filePath = HttpContext.Current.Server.MapPath("~/Image/" + postedFile.FileName+date+ extension);
postedFile.SaveAs(filePath);
}
}
var message1 = string.Format("Image Updated Successfully.");
return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
}
var res = string.Format("Please Upload a image.");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
catch (Exception ex)
{
var res = string.Format("some Message");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
}
现在 FileName 正在从文件名中获取。但我需要在文件名中添加日期。
我尝试这样做:
var date = DateTime.Now.ToString();
var filePath = HttpContext.Current.Server.MapPath("~/Image/" + postedFile.FileName+date+ extension);
但它不起作用。发送图片时出现错误
我该怎么做?
感谢您的帮助。
【问题讨论】:
-
请显示您遇到的错误。
-
问题已经解决了
-
对不起,它出现在审核队列中,没有显示是否已被回答。通常,每当您收到错误时,您都希望将其包含在您的问题中。
标签: c# asp.net asp.net-mvc-4 asp.net-web-api