Titti Towel
Titti Towel

Reputation: 121

image File is not saving into Server "Img" Folder

[HttpPost]
public JsonResult SavePhoto(string base64)
{
    string file = "test.jpg";
    string Imgpath = Path.Combine(Server.MapPath("~/Img/"), Path.GetFileName(file));
    System.IO.File.WriteAllBytes(Imgpath, Convert.FromBase64String(base64));

    return Json(new { status= true},JsonRequestBehavior.DenyGet);
} 

I make a request from Postman and send a Base64 string to the calling Action it's return "true" and Image saving locally but no Image has been saved to the server "Img" Folder. If there is no issue with my code then why Image is not saving into the server "Img" Folder

Upvotes: 0

Views: 1678

Answers (2)

vrharilal
vrharilal

Reputation: 126

You can try this code, its working fine in my project

[HttpPost]
    public JsonResult SavePhoto(string base64)
    {
        string fileName = "test.jpg";
        var path = HttpContext.Current.Server.MapPath("~/Uploads/Employee/");
        string uniqueFileName = Guid.NewGuid() + "_" + fileName;

        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        byte[] bytes = Convert.FromBase64String(base64);
        var fs = new FileStream(path + "/" + uniqueFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        fs.Write(bytes, 0, bytes.Length);
        fs.Flush();
        fs.Close();
        fs.Dispose();

        return Json(new { status = true }, JsonRequestBehavior.DenyGet);
    }

Upvotes: 2

Supraj V
Supraj V

Reputation: 977

Check This

public JsonResult SavePhoto(string base64)
    {
        byte[] bytes = Convert.FromBase64String(base64);
        MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length);
        ms.Write(bytes, 0, bytes.Length);
        Image image = Image.FromStream(ms, true);
        string filestoragename = Guid.NewGuid().ToString() + ".jpeg";
        string outputPath = HttpContext.Current.Server.MapPath(@"~/Img/" + filestoragename);
        image.Save(outputPath, ImageFormat.Jpeg);
        return Json(new { status = true }, JsonRequestBehavior.DenyGet);

    }

Make sure you have created Img folder in your project solution

You need to use these references

using System.IO;
using System.Drawing;
using System.Web;
using System.Drawing.Imaging;
using System.Web.Http;

Upvotes: 1

Related Questions