首页 > 解决方案 > 带有图像的 HTTP POST 数据从 WebForm 到 .NET Web API,JSON 太大

问题描述

我正在使用需要将图像发送到 API 方法的 C# webform 应用程序。POST 在 webform 应用程序中执行并命中 API POST 方法,但 API 方法中的 JObject 参数为 NULL,但 webform 中的 JSON 数据创建没有问题。如果我传递除图像之外的所有数据,则 JObject 不为空,这告诉我图像(字节)太大而无法传递。我尝试压缩图像但不起作用,尝试将 enctype="multipart/form-data" 作为表单的一部分,我还在网络中将 jsonSerialization maxJsonLength="2147483647" 增加到 int32.max API 应用程序和 Web 应用程序中的 .config 但这不起作用。不知道接下来要尝试什么,但会继续搜索,任何帮助将不胜感激。网络表单和 API 控制器代码发布在下面:

按钮点击代码:

    HttpPostedFile _File = ImageUpload.PostedFile;
    int fileSize = _File.ContentLength;
    string contentType = _File.ContentType;
    string fileName = _File.FileName;

    byte[] bytes;

    using (BinaryReader br = new BinaryReader(_File.InputStream))
    {
        bytes = br.ReadBytes(_File.ContentLength);
    }

    ImageModel _ImgModel = new ImageModel();

    _ImgModel.Name = fileName;
    _ImgModel.ContentType = contentType;
    _ImgModel.Data = bytes;
    _ImgModel.idPersonFK = 1;

    string apiURL = "http://localhost:XYZZ/api/Image/InsertImage";
    WebRequest request = WebRequest.Create(apiURL);
    request.Method = "POST";
    string jsonData = JsonConvert.SerializeObject(_ImgModel);
    byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
    request.ContentType = "application/json";
    request.ContentLength = byteArray.Length;
    Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);

    dataStream.Close();

    WebResponse response = request.GetResponse();

    using (dataStream = response.GetResponseStream())
    {
        // Open the stream using a StreamReader for easy access.  
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.  
        string responseFromServer = reader.ReadToEnd();
    }

    response.Close();

型号类:

public class ImageModel 
{
    public long ImageID { get; set; }
    public string Name { get; set; }
    public string ContentType { get; set; }
    public byte[] Data { get; set; }
    public Nullable<long> idPersonFK { get; set; }
}

API 控制器

[HttpPost]
[Route("api/Image/InsertImage")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public HttpResponseMessage Insert(JObject input)
{
    try
    {
        //Code that will insert the image but input parameter is NULL;
    }
    catch (Exception ex)
    {
        logger.Error(ex, ex.Message);
        return Request.CreateResponse(HttpStatusCode.BadRequest, "");
    }
    finally
    {

    }
}

网络配置

jsonSerialization maxJsonLength="2147483647"

标签: webformsjson.nethttpwebrequestasp.net-apicontrollerimage-file

解决方案


我的错(早上没有喝咖啡),如果我尝试上传的图片大小在 2mb 而不是 5mb 左右会有所帮助,所以我需要限制我的图片上传大小。

在我的情况下,因为我需要上传最少 3 张图片,最多 6 张图片,所以它们必须一张一张地完成,因为 JSON 字符串太大了。

如果有更好或更有效的方法,请随时给我留言。

谢谢你。


推荐阅读