admin管理员组

文章数量:1391929

   public async Task<CommonResponse> Registration()
  {
   CommonResponse response = new CommonResponse();
 try
 {
     if (!Request.Content.IsMimeMultipartContent())
     {
         response.ResponseMessage = "Not data found in request.";
         return response;
     }
     // Get the server-mapped path 
     var tempPath = HttpContext.Current.Server.MapPath("~/Uploads/Temp");

     // Ensure the directory exists
     if (!Directory.Exists(tempPath))
     {
         Directory.CreateDirectory(tempPath);
     }

     var provider = new MultipartFormDataStreamProvider(tempPath);

     await Request.Content.ReadAsMultipartAsync(provider);

     // Retrieve JSON data
     var jsonData = provider.FormData["VoterDetails"];
     var voterInfo = JsonConvert.DeserializeObject<VoterInfo>(jsonData);
     if (voterInfo != null)
     {
         response = _erp.RegisterVoter(voterInfo);
         if(response.ResponseCode == 1)
         {
             // Process uploaded images
             var folderExists = Lib.CreateFolder(HttpContext.Current.Server.MapPath("~/Uploads/Voters/" + response.IdString));
             if (folderExists)
             {
                 var storagePath = HttpContext.Current.Server.MapPath("~/Uploads/Voters/" + response.IdString);
                 List<string> savedFiles = new List<string>();
                 foreach (var file in provider.FileData)
                 {
                     // Extract original filename
                     string originalFileName = file.Headers.ContentDisposition.FileName.Trim('"');
                    // string fileExtension = Path.GetExtension(originalFileName);

                     // Generate new unique filename
                     string newFileName = response.IdString + originalFileName;
                     string finalPath = Path.Combine(storagePath, newFileName);

                     // Move file to correct path
                     File.Move(file.LocalFileName, finalPath);
                     savedFiles.Add(finalPath);
                 }
             }
             else
             {
                 response.ResponseMessage = "Folder not found";
             }
         }
         else
         {
             response.ResponseMessage = "Error." + response.ResponseMessage;
         }
     }
     else
     {
         response.ResponseMessage = "Failed to save voter details.";
     }
 }
 catch (Exception ex)
 {
    response.ResponseMessage = $"Error : {ex.Message}";
 }
 return response;

}

-- Web api method ---

  Future<http.Response> formData(
  List<File?> files, String data, String endpoint) async {
try {
  var url = "${Constants.baseUrl()}$endpoint";
  var request = http.MultipartRequest('POST', Uri.parse(url));
  request.headers.addAll({
    "Content-Type": "multipart/form-data",
    "Accept": "application/json",
  });


  request.fields['VoterDetails'] = data;

  // Change files name to identify the file on the server side
  // Don't change the order and the modifed name of the files.
  // If you wish to, u will have to change the server side code as well
  List<String> filesNames = [
    "_Photo.jpg",
    "_Graduation.jpg",
    "_HighSchool.jpg",
    "_Aadhaar.jpg"
  ];


  for (int i = 0; i < files.length; i++) {
    if (files[i] != null) {
      // Rename the file before sending to the server
      File renamedFile = File("${files[i]!.parent.path}/${filesNames[i]}");
      await files[i]!.copy(renamedFile.path);
      request.files.add(await http.MultipartFile.fromPath(
        'file',
        renamedFile.path,
        contentType: MediaType('image', 'jpeg'),
      ));
    }
  }

  var streamedResponse = await request.send();
  var response = await http.Response.fromStream(streamedResponse);
  return response;
} catch (e) {
  rethrow;
}

}

<configuration>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=DigiVoterServer\SQLSERVER_2K17,27545; Initial Catalog=DigiVoterDB;User ID=userDigiVoterDb;Password=DbXrIU6EpfDheo;Persist Security Info=True;Pooling=true;Max Pool Size=100;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2"/>
      <!-- Increase max request length (in KB) -->
      <httpRuntime targetFramework="4.7.2" maxRequestLength="2147483647" executionTimeout="600"/>
  </system.web>
  <system.webServer>
      <security>
          <requestFiltering>
              <!-- Increase max file size limit (in Bytes) -->
              <requestLimits maxAllowedContentLength="2147483648" />
          </requestFiltering>
      </security>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
      <remove name="OPTIONSVerbHandler"/>
      <remove name="TRACEVerbHandler"/>
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f"/>
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Web.Infrastructure" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-5.2.9.0" newVersion="5.2.9.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>

I am working on a Flutter app that uploads voter details along with 4 images to an ASP.NET (non-core) Web API. The API call works fine on localhost, but on the live server, it fails when uploading large image sizes. If the images are small, the upload works successfully.

The error message I get is: "Error reading MIME multipart body part."

I've been troubleshooting this issue for three days but still haven't found a solution. What could be causing this issue, and how can I resolve it?

本文标签: aspnetError reading MIME multipart body part in flutterStack Overflow