Reputation: 2282
So, I want to upload an image file and save it to some path. It works on first try, but if want to upload it second time, even after I close the app and run it again, it getting an error
The process cannot access the file '..mypath..' because it is being used by another process
How do I solve this?
here is my code
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();
}
Can someone help me? maybe my code for upload image is wrong, so how to do it right?
I'm using C# asp .net mvc
sorry for my english..
Upvotes: 1
Views: 772
Reputation: 412
I want to know how you call this API request. But try this code. The image send within the request body here.
[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;
}
Upvotes: 1
Reputation: 211
Just read that post again, it will help you.
How save uploaded file? c# mvc
And also, be sure about your save name isn't exsist and any software doesnt use it.
var fileName = datetime + "_" + Path.GetFileName(file.FileName);
Check this line and server path.
Upvotes: 0