HttpClient: The uri string is too long

后端 未结 4 750
青春惊慌失措
青春惊慌失措 2020-12-17 10:00

Given the following attempt to post data to a web service that generates PDF files, PDF rocket (which is awesome by the way).

I get the err

4条回答
  •  情深已故
    2020-12-17 10:52

    I just solved a similar problem. For me I was integrating with a backend I didn't control and had to POST file along with form data (eg customerID) as form variables. So switching to JSON or Multipart would break the backend I didn't control. The problem was that large files would cause the FormUrlEncodedContent to throw an error saying "The uri string is too long".

    This is the code that solved it for me after two days of effort (note still needs to be tweaked to be ASYNC).

    private string UploadFile(string filename, int CustomerID, byte[] ImageData) {
    
            string Base64String = "data:image/jpeg;base64," + Convert.ToBase64String(ImageData, 0, ImageData.Length);
    
            var baseAddress = new Uri("[PUT URL HERE]");
            var cookieContainer = new CookieContainer();
            using (var handler = new HttpClientHandler() { AllowAutoRedirect = true, UseCookies = true, CookieContainer = cookieContainer })
            using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
            {
    
                try {
    
                    //ENCODE THE FORM VARIABLES DIRECTLY INTO A STRING rather than using a FormUrlEncodedContent type which has a limit on its size.        
                    string FormStuff = string.Format("name={0}&file={1}&id={2}", filename, HttpUtility.UrlEncode(Base64String), CustomerID.ToString());
                    //THEN USE THIS STRING TO CREATE A NEW STRINGCONTENT WHICH TAKES A PARAMETER WHICH WILL FormURLEncode IT AND DOES NOT SEEM TO THROW THE SIZE ERROR
                    StringContent content = new StringContent(FormStuff, Encoding.UTF8, "application/x-www-form-urlencoded");
    
                    //UPLOAD
                    string url = string.Format("/ajax/customer_image_upload.php");
                    response = client.PostAsync(url, content).Result;
                    return response.Content.ToString();
    
                }
                catch (Exception ex) {
                    return ex.ToString();
                }
    
    
    
            }
    
        }
    

提交回复
热议问题