Best way to save an image?

2019-09-11 23:48发布

I have an asp.net mvc application that allows images to be uploaded. I am wondering what is the best way to do it.

Right now I have this

HttpPostedFileBase uploadedImg = Session[SessionImgKey] as HttpPostedFileBase;

if (uploadedImg != null)
{
    string fileName = CreateFile(MyField.Name, uploadedImg);
    tableA.ImagePath = String.Concat(ImgFolderPathLoctaion, "\\", fileName);
}

This is fine but I want to move it my service layer and I don't want to have in import a web.dll into my service layer project.

So should I be using a stream? or something like Image Save (I think this might be more geared for images through the paint class not images uploaded.

2条回答
Luminary・发光体
2楼-- · 2019-09-12 00:33

If you need to pass the file down to your service layer, use the InputStream property of HttpPostedFileBase to pass a stream. By doing it this way, your service layer does not know of your web/presentation layer.

查看更多
3楼-- · 2019-09-12 00:36

You can get the image stream from the posted file, convert it in an image (System.Drawing) and then save it:

var stream = uploadedImg.InputStream;
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
//convert stream into image
Image myImage = Image.FromStream(new MemoryStream(buffer));
myImage.Save("c:\myimage.jpg");
查看更多
登录 后发表回答