5

我一直在为客户构建一个功能,使他们能够从 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");

如果有一种方法可以使此代码正常工作,或者如果有更好的方法可以做到这一点,请提供帮助。

4

2 回答 2

10

StreamReader 旨在阅读文本。

改变:

StreamReader rdr = new StreamReader(image);
byte[] fileData = Encoding.UTF8.GetBytes(rdr.ReadToEnd());

byte[] fileData = File.ReadAllBytes(image);
于 2012-09-12T02:28:27.693 回答
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();

        }
    }
于 2016-09-21T01:35:56.130 回答