我在画布元素中有一个图像文件,在asp.net后面的代码中可以得到该文件。现在我想将它保存到项目中的一个文件夹中,但是文件流总是将它保存到c驱动器中。我做什么好?
[WebMethod()]
public void SaveUser(string imageData)
{
//Create image to local machine.
string fileNameWitPath = path + "4200020789506" + ".png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
// Save fileNameWitPath variable to Database.
}发布于 2017-02-08 18:51:06
我就是这样做的,而且效果很好。对于您来说,filePath/filename = fileNameWitPath。对您拥有的每个文件执行此操作。希望它对你有用。如果你需要更多的信息,我很乐意帮忙。
using (var stream = File.Create(filePath + filename))
{
attachment.ContentObject.DecodeTo(stream, cancel.Token);
}发布于 2017-02-08 08:13:05
下面是一个示例,说明如何将文件保存到项目目录中的Images文件夹中。
var fileName = "4200020789506.png";
var base64String = SOME_REALLY_LONG_STRING;
using (var s = new MemoryStream(Convert.FromBase64String(base64String)))
using (var f = new FileStream(Path.Combine(Server.MapPath("~/Images"), fileName), FileMode.Create, FileAccess.Write))
{
s.CopyTo(f);
}发布于 2017-02-08 06:48:19
我只能想象您的path变量指向C:\驱动器。
您需要将path变量设置为您想要的位置,例如:
public void SaveUser(string imageData)
{
path = @"C:\YourCustomFolder\"; // your path needs to point to the Directory you want to save
//Create image to local machine.
string fileNameWitPath = path + "4200020789506" + ".png";
//chekc if directory exist, if not, create
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
// Save fileNameWitPath variable to Database.
}我还提供了一项检查,以查看您的目录是否存在,如果不存在,它将在C驱动器上创建一个名为“YourCustomFolder”的文件夹,在该文件夹中保存图像。
如果要将图像保存到项目中的文件夹中,我建议使用Server.MapPath(~/YourFolderInApplication)
https://stackoverflow.com/questions/42106232
复制相似问题