我想使用NancyFX在服务器上上传文件。我这样做:
var fileStream = File.Create(path_to_file);
file.Value.Seek(0, SeekOrigin.Begin);
file.Value.CopyTo(fileStream);
fileStream.Close();
Also i tried:
byte[] buffer;
using (var memoryStream = new MemoryStream())
{
file.Value.Seek(0, SeekOrigin.Begin);
file.Value.CopyTo(memoryStream);
buffer = memoryStream.ToArray();
}
MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length);
ms.Position = 0;
Image img = Image.FromStream(ms, true);
img.Save(path);
:
File.WriteAllBytes(coverPath, buffer);
在我的Windows电脑上,它工作得很好。在Linux服务器上,镜像正在保存,但是镜像内容与原始镜像不匹配。这里是图片:原始图像,即上传:https://i.stack.imgur.com/mTsE2.jpg保存图片:https://i.stack.imgur.com/ORKn1.jpg如果图像大小为<900kb,图像保存良好,但有时也会出现线条。请帮助。
据我所知你有一个fileStream你想把它保存为Image
这是一个和平的代码,在Windows 8 .net 4.5和Ubuntu 12 TLS与mono JIT编译器版本2.10.8.1
class Program
{
static void Main(string[] args)
{
string fileName = @"img/mTsE2.jpg";
string destimationImage = @"img/dest.jpg";
string appPath = AppDomain.CurrentDomain.BaseDirectory;
string pathToFile = Path.Combine(appPath, fileName);
if (!File.Exists(pathToFile))
{
Console.WriteLine("Cant find file {0}", pathToFile);
Console.ReadLine();
return;
}
MemoryStream memoryStream = new MemoryStream();
using (FileStream fileStream = File.Open(pathToFile, FileMode.Open))
{
Console.WriteLine("Source length: {0}", fileStream.Length);
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, (int)fileStream.Length);
memoryStream.Write(bytes, 0, (int)fileStream.Length);
}
Console.WriteLine("memoryStream length {0}", memoryStream.Length);
string destPath = Path.Combine(appPath, destimationImage);
CopyAsImage(destPath, memoryStream);
Console.WriteLine("Done! Check file {0}",destPath);
Console.ReadLine();
}
private static void CopyAsImage(string fileName, Stream stream)
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
Image image = Image.FromStream(stream, true, true);
image.Save(fileName);
}
}
如果仍然不起作用,请注意大小。事实上,int是Int32类型对于最大2+Gigs的字节数组应该没问题