照片图像上传并存储在会话中

时间:2019-03-18 12:23:48

标签: c# asp.net model-view-controller image-upload

对于客户表单,我需要上传照片并将其存储在文件系统中,但是在填充并提交了整个表单之后。

我正在使用ajax文件上传功能通过HttpPostedFileBase上传文件,我尝试将其存储在会话变量中,并在提交整个表单后将其从会话保存到文件中。试图将其转换为字节数组,但是没有运气。

找不到任何可用于此目的的示例。

请有人提供一些示例如何将HttpPostedFileBase fileUpload转换为字节数组并返回,以便以后可以将其存储在服务器上的文件中吗?

1 个答案:

答案 0 :(得分:0)

找到了解决该问题的方法;将文件转换为Base64,将其存储在会话变量中,并在提交表单时从会话中检索它:

//convert to Base64
System.IO.Stream fileStream = model.PersonPhotoFile.InputStream;
Byte[] fileToByte = new Byte[model.PersonPhotoFile.ContentLength];
model.PersonPhotoFile.InputStream.Position = 0;
model.PersonPhotoFile.InputStream.Read(fileToByte, 0, model.PersonPhotoFile.ContentLength);
string base64stringPhoto = Convert.ToBase64String(fileToByte);
fileStream.Close();

//convert from Base64 and write to file
Byte[] fileFromBytes = Convert.FromBase64String(base64stringPhoto);
System.IO.File.WriteAllBytes("D:\\Temp\\temp_from_base64.jpg", fileFromBytes);
相关问题