图像文件没有保存到服务器" Img"夹

时间:2016-12-07 12:44:09

标签: c# asp.net-mvc

[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);
} 

我向Postman发出请求,并向调用的Action发送一个Base64字符串它返回" true" 并在本地保存图像但没有保存图像服务器" Img" 文件夹。如果我的代码没有问题,那么为什么Image没有保存到服务器" Img" 文件夹

2 个答案:

答案 0 :(得分:2)

您可以尝试使用此代码,它在我的项目中正常工作

[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);
    }

答案 1 :(得分:1)

检查此

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);

    }

确保在项目解决方案中创建了Img文件夹

您需要使用这些参考

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