使用双内存和文件流写入2个文件

时间:2016-12-25 18:59:32

标签: c# .net asp.net-mvc

我需要按目录产品保存2张照片 - 小而标准。但是当我使用SavePhoto方法时第二次得到ArgumentException:

  

异常:System.ArgumentException:未知参数

问题解决了!对于同样问题的人:

HttpPostedFileBase文件InputStream应该立刻使用,我们必须修改这个字段以获取其他MemoryStream的缓冲区,所以方法现在将是1而不是2

控制器:

[HttpPost]
public ActionResult UploadProdImages(IEnumerable<HttpPostedFileBase> photos, int pid)
{                  
    if (photos != null)
    {
        foreach (var file in photos)
        {                    
            _pRepository.SavePhoto(file, pid);  
    ------> _pRepository.SavePhoto(file, pid,"small"); <----- //Remove this              
        }
    }

    return Json(new { pimgid = pid});
}

服务类:

public void SavePhoto(HttpPostedFileBase file, int pid,string t)
{                     
    string dirPath = null;
    byte[] istream = null;
    string filePath = null;
    string filePathSmall = null;
    string dirPathSmall = null;

    // file.InputStream using only once! 
    istream = new WebImage(file.InputStream).Resize(1920, 1080,true,true).GetBytes(); 
    //implementing if need Check directory if exist and create if not
    dirPath = HttpContext.Current.Server.MapPath("~/Content/Files/Product/" + pid);              
    dirPathSmall = HttpContext.Current.Server.MapPath("~/Content/Files/Product/" + pid+"/200x150");

    //Full path's with file name
    filePath = Path.Combine(dirPath, GetRandomName() + Path.GetExtension(file.FileName));
    filePathSmall = Path.Combine(dirPathSmall, GetRandomName() + Path.GetExtension(file.FileName));
    //Save first time standart size photo
    using (MemoryStream ms = new MemoryStream(istream))
    {
        using (FileStream fs = new FileStream(filePath, FileMode.Create))
        {
             fs.CopyTo(ms);
             ms.CopyTo(fs);
        }
    }
    //Save second time small photo with same input - istream
    istream = new WebImage(istream).Resize(150, 150,false).GetBytes();
    using (MemoryStream ms = new MemoryStream(istreamSmall))
    {
        using (FileStream fs = new FileStream(filePathSmall, FileMode.Create))
        {
             fs.CopyTo(ms);
             ms.CopyTo(fs);
        }
    }
}

那么如何合并MemoryStream(使用不同的对象&)和FileStream(使用不同的路径)?

2 个答案:

答案 0 :(得分:0)

也许我的想法太简单但你没有在第一次通话中将第三个参数(字符串)传递给函数......

答案 1 :(得分:0)

可能是因为FileStream在通过using语句

处理时自动关闭了底层流