C# 通过流上传图片 批量上传图片

 注意此方案为流式读取图片文件并上传!!不是formdata!!


/// 图片文件夹路径
/// 图片名称
public void UpLoadFile(string imagesPath, List files)
{
///你的服务器API
    string srcurl = "http://81.70.218.18:10086/upload/"
    int count = 1;
    foreach (string imageName in files)
    {
        string name = imageName;
        string url = null;
        //+  加号特殊处理
        if (name.Contains("+"))
        {
            url = srcurl + "name=" + name.Replace("+", "%2B");
        }
        else
        {
            url = srcurl + "name=" + name;
        }

        FileStream fs = new FileStream(imagesPath + name, FileMode.Open);
        byte[] data = new byte[fs.Length];
        fs.Read(data, 0, data.Length);
        fs.Close();

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "image/jpeg";
        request.Method = "POST";
        Encoding encoding = Encoding.UTF8;
        request.ContentLength = data.Length;
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(data, 0, data.Length);
        requestStream.Close();


        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader streamReader = new StreamReader(response.GetResponseStream(), encoding);
        string retString = streamReader.ReadToEnd();
        streamReader.Close();

        Console.WriteLine((count++) + "/" + files.Count);

    }
}

你可能感兴趣的:(c#,开发语言)