Upload files with HTTPWebrequest (multipart/form-data)

后端 未结 21 2561
独厮守ぢ
独厮守ぢ 2020-11-21 04:53

Is there any class, library or some piece of code which will help me to upload files with HTTPWebrequest?

Edit 2:

I do not

21条回答
  •  情话喂你
    2020-11-21 05:11

    I can never get the examples to work properly, I always receive a 500 error when sending it to the server.

    However I came across a very elegant method of doing it in this url

    It is easily extendible and obviously works with binary files as well as XML.

    You call it using something similar to this

    class Program
    {
        public static string gsaFeedURL = "http://yourGSA.domain.com:19900/xmlfeed";
    
        static void Main()
        {
            try
            {
                postWebData();
            }
            catch (Exception ex)
            {
            }
        }
    
        // new one I made from C# web service
        public static void postWebData()
        {
            StringDictionary dictionary = new StringDictionary();
            UploadSpec uploadSpecs = new UploadSpec();
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] bytes;
            Uri gsaURI = new Uri(gsaFeedURL);  // Create new URI to GSA feeder gate
            string sourceURL = @"C:\FeedFile.xml"; // Location of the XML feed file
            // Two parameters to send
            string feedtype = "full";
            string datasource = "test";            
    
            try
            {
                // Add the parameter values to the dictionary
                dictionary.Add("feedtype", feedtype);
                dictionary.Add("datasource", datasource);
    
                // Load the feed file created and get its bytes
                XmlDocument xml = new XmlDocument();
                xml.Load(sourceURL);
                bytes = Encoding.UTF8.GetBytes(xml.OuterXml);
    
                // Add data to upload specs
                uploadSpecs.Contents = bytes;
                uploadSpecs.FileName = sourceURL;
                uploadSpecs.FieldName = "data";
    
                // Post the data
                if ((int)HttpUpload.Upload(gsaURI, dictionary, uploadSpecs).StatusCode == 200)
                {
                    Console.WriteLine("Successful.");
                }
                else
                {
                    // GSA POST not successful
                    Console.WriteLine("Failure.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
    

提交回复
热议问题