2016-12-07 101 views
0
[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); 
} 

我做从邮差的请求,并发送一个Base64字符串给调用操作它返回“真”和图像保存在本地,但没有图片已被保存到服务器“Img”文件夹。如果我的代码,那么为什么图像中没有保存到服务器“图”文件夹没有问题图像文件没有保存到服务器“图”文件夹

+0

您是否对该IIS用户的该文件夹的服务器拥有写入权限? –

+0

如何写权限...? –

+0

看看这个答案http://stackoverflow.com/questions/26849554/createdirectory-at-server-in-a-shared-machine/26850094#26850094 –

回答

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

    } 

确保你已经创建图文件夹中的项目解决方案

你需要使用这些引用

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

HttpContext.Current.Server.MapPath(@“〜/ Img /”+ filestoragename)。有错误行说错误'System.Web.HttpContextBase'不包含'Current'的定义,并且没有找到接受'System.Web.HttpContextBase'类型的第一个参数的扩展方法'Current'(你是否遗漏了使用指令或程序集引用?) –

+1

检查我编辑的答案 –

+0

我已经在使用这些引用,但仍然收到错误。我的新增参考资料是... using System; using System.Collections.Generic;使用System.Linq的 ; using System.Web; using System.Web.Mvc; 使用共享; 使用Donation.DataLayer; 使用AdminModel; using System.Web.Security;使用System.IO的 ; using System.Drawing.Imaging; using System.Drawing; –

2

可以TR y此代码,其在我的项目中工作正常

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