所以,我想上传一个图像文件并将其保存到某个路径。它首先尝试,但如果想第二次上传,即使我关闭应用程序并再次运行它,它会收到错误
The process cannot access the file '..mypath..' because it is being used by another process
我该如何解决这个问题?
这是我的代码
public ActionResult UploadImage(HttpPostedFileBase file, string text)
{
if (file != null && file.ContentLength > 0)
{
var fileName = datetime + "_" + Path.GetFileName(file.FileName);
log_file = fileName;
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path); //error
Bitmap bmp = new Bitmap(path);
bmp = EmbedText(bmp, "Some Text");
var outputFileName = Path.Combine(Server.MapPath("~/StegoImages/"), fileName); ;
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
bmp.Save(memory, ImageFormat.Png);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
string coba = extractText(bmp);
}
else
{
TempData["flag_no_file"] = '1';
return RedirectToAction("UploadImage");
}
return View();
}
有人能帮助我吗?也许我上传图片的代码是错误的,那么怎么做呢?
我正在使用C#asp .net mvc
抱歉我的英语..答案 0 :(得分:1)
我想知道您如何调用此API请求。 但试试这个代码。图像在请求体内发送。
[HttpPost]
public HttpResponseMessage UploadJsonFile()
{
userID = "any name";
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
try
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/ProfileImages/"+ userID);
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
else
{
DirectoryInfo directory = new DirectoryInfo(filePath);
FileInfo[] files = directory.GetFiles("*.jpg");
foreach (FileInfo fil in directory.GetFiles())
{
fil.Delete(); //Delete existing image...
}
}
Random rnd = new Random();
int num = rnd.Next(1, 100);
postedFile.SaveAs(filePath +"/"+ num+postedFile.FileName);
}
catch (Exception e)
{
ExceptionLogging.SendErrorToText(e);
}
}
}
return response;
}
答案 1 :(得分:0)
再次阅读该帖子,它会对你有帮助。
How save uploaded file? c# mvc
此外,请确保您的保存名称不是exsist,并且任何软件都不使用它。
var fileName = datetime + "_" + Path.GetFileName(file.FileName);
检查此行和服务器路径。