locked
File Upload in API. Dotnet core Web controller or WPF Windows App RRS feed

  • Question

  • User1064314092 posted

    I am trying to post File in API. in the Dotnet core Web controller. and Successfully upload Files in dot net core. but i am Tired in asp.net. in from data

    API Controller

    public class TestDocumentModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public IFormFile formFiles { get; set; }
    }

    API Controller

    public async Task<IActionResult> UploadModelFiles([FromForm]TestDocumentModel models)
        {
    
            var filePath = Path.Combine(@"Custome File Save Path");
    
            if (models.formFiles != null)
            {
                long sizeOfFile = models.formFiles.Length;
                if (filePath.Length > 0)
                {
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    
                       if (Directory.Exists(filePath))
                       {
                          using (var fileStream = new FileStream(Path.Combine(filePath, models.formFiles.FileName), FileMode.Create))
                          {
                            await models.formFiles.CopyToAsync(fileStream);
                          }
                      }
    } } return Ok(new { sizeOfFile, filePath }); } else { long fileSize = 0; filePath = "File note Found"; return Ok(new { fileSize, filePath }); } }

    Web Controller or WPF Windows Application Class

    obj = new TestModelClass();
    
    if (dlg != null)
    {
    using (var httpClient = new HttpClient())
    {
    string fileName = dlg.SafeFileName;
    using (var content = new MultipartFormDataContent())
    {
    obj.Id = int.Parse(tb_id.Text);
    obj.Name = tb_name.Text;
    FileStream fileStream = File.OpenRead(dlg.FileName);
    HttpContent fileStreamContent = new StreamContent(fileStream);
    
    content.Add(new StringContent(Convert.ToString(obj.Id)), "Id");
    content.Add(new StringContent(Convert.ToString(obj.Name)), "Name");
    fileStreamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "formFiles", FileName = fileName };
    fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    
    content.Add(fileStreamContent);
    
    using (var response = await httpClient.PostAsync("https://localhost:44359/weatherforecast/UploadModelFiles", content))
    {
    string apiResponse = await response.Content.ReadAsStringAsync();
    }
    }
    }
    }

    File Post in Api With postman 

    https://i.stack.imgur.com/kEKpR.png

    File Post in Api With WPF or Web app

    https://i.stack.imgur.com/Rkyhp.png

    Wednesday, February 19, 2020 9:41 AM

All replies

  • User-474980206 posted

    you are doing a multipart form upload. each form field and file is a separate part (with boundary and mime-header). StringContent() is for text data (text files or text fields). you need to use one of the binary content types. say StreamContent() or ByteArrayContent() 

    Wednesday, February 19, 2020 4:54 PM
  • User1064314092 posted

    I already try this way.

        byte[] data;
        using (var br = new BinaryReader(dilog.FileName.OpenReadStream())) 
        {
            data = br.ReadBytes((int)dilog.FileName.OpenReadStream().Length);
        }
       ByteArrayContent bytes = new ByteArrayContent(data);
    
    ////This Line
       content.Add(data,"formFiles",dilog.FileName);

    Please can you provide the source code or link ? thanks

    Wednesday, February 19, 2020 5:48 PM
  • User665608656 posted

    Hi rezaulkhan111,

    Your current problem is not file conversion, but the mismatch between the name of the parameters your API accepts and the one you pass.

    You need to change the receiving parameter name of the current API Controller method to be consistent with the name parameter value of MultipartFormDataContent.

    API Controller:

    public async Task<IActionResult> UploadModelFiles([FromForm]TestDocumentModel formFiles)
    {
     ....
    }
       byte[] data;
        using (var br = new BinaryReader(dilog.FileName.OpenReadStream())) 
        {
            data = br.ReadBytes((int)dilog.FileName.OpenReadStream().Length);
        }
       ByteArrayContent bytes = new ByteArrayContent(data);
    
    ////This Line
       content.Add(data,"formFiles",dilog.FileName);

    Best Regards,

    YongQing.

    Friday, February 21, 2020 10:35 AM
  • User1064314092 posted

    Thanks For Yor Replay. and now I am Fix the problem

    Sunday, February 23, 2020 5:38 AM