我一直致力于为客户构建一个功能,使他们能够从www.site1.com上传图像,将图像URL存储到数据库并将图像存储到www.site2.com/images上的文件中。我已经设法将文件上传到目标位置,但是当我尝试打开并查看图像时,据说它包含错误。我从来没有真正使用过图像,所以我很茫然。
这是用于上传文件的方法:
public static void UpLoadImage(Stream image, string target)
{
FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://www.site2.com/images/" + target);
req.UseBinary = true;
req.Method = WebRequestMethods.Ftp.UploadFile;
req.Credentials = new NetworkCredential("myUser", "myPass");
StreamReader rdr = new StreamReader(image);
byte[] fileData = Encoding.UTF8.GetBytes(rdr.ReadToEnd());
rdr.Close();
req.ContentLength = fileData.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(fileData, 0, fileData.Length);
reqStream.Close();
}
这是从(image1是HttpPostedFileBase)调用方法的地方:
myObject.UpLoadImage(image1.InputStream, storedTL.ID + "-1.png");
如果有一种方法可以使这段代码有效,或者有更好的方法可以做到这一点,请提供帮助。
答案 0 :(得分:10)
StreamReader旨在阅读文字。
变化:
StreamReader rdr = new StreamReader(image);
byte[] fileData = Encoding.UTF8.GetBytes(rdr.ReadToEnd());
到
byte[] fileData = File.ReadAllBytes(image);
答案 1 :(得分:0)
老问题,但我今天在这个问题上失去了一些时间,使用 ReadAllBytes 对我来说不是一个选项,所以我只得处理Streams。经过一些研究,我是如何找到解决方案的:
public void UploadToFTP(Stream stream, string ftpPath)
{
Stream requestStream = null;
try
{
Uri uri = GetServerUri(ftpPath);
FtpWebRequest request = Connect(uri); //here I set user/pwd/etc
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.ContentLength = stream.Length;
requestStream = request.GetRequestStream();
//Avoid to write zero length files in destiny.
//If you have read the stream before for any reason (as a convertion to Bitmap to extract dimensions, for example)
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(requestStream);
}
catch (WebException ex)
{
//do something
}
finally
{
if (requestStream != null)
requestStream.Close();
}
}