C#post上传文件,post发送文件(Http Post),带其他参数

时间:2025-03-27 14:40:39

除了发送的文件主体之外,还能附加一些其他参数,例如本例中图片文件是主体,然后另外加了一个token参数,值为方法参数token,其他参数以此类推。

public static string HttpPost(string url, string filepath, string filename, string token)
{   
    string strResult;      
    try      
    {        
        FileStream fs = new FileStream(filepath, , );        
        byte[] bytebuffer;        
        bytebuffer = new byte[];        
        (bytebuffer, 0, (int) );        
        ();              
        string boundary = ("X");        
        string Enter = "\r\n";        
        string strContent1 = "--" + boundary + Enter + "Content-Type: application/octet-stream" + Enter + "Content-Disposition: form-data; filename=\"" + "" + filename + "" + "\"; name=\"file\"" + Enter + Enter;        
        string strContent2 = Enter + "--" + boundary + Enter + "Content-Type: text/plain" + Enter + "Content-Disposition: form-data; name=\"token\"" + Enter + Enter + "" + token + "" + Enter + "--" + boundary + "--";        
        byte[] strContentByte1 = Encoding.(strContentByte1);
        byte[] strContentByte2 = Encoding.(strContentByte2);
        HttpWebRequest request = (HttpWebRequest)(url);
         = "POST";
         = "multipart/form-data;boundary=" + boundary;
        Stream myRequestStream = ();
        (strContentByte1, 0,);
        (bytebuffer, 0, );
        (strContentByte2, 0, );       
        HttpWebResponse response = (HttpWebResponse) ();        
        Stream streamReceive = ();        
        Encoding encoding = Encoding.UTF8;        
        StreamReader streamReader = new StreamReader(streamReceive, encoding);        
        strResult = ();        
        ();        
        ();        
        return strResult;      
    }      
    catch(Exception ex)      
    {        
        return ;
    }      
    return strResult;    
}