Home > front end >  Web API & Postman - Add Multiple Attachments
Web API & Postman - Add Multiple Attachments

Time:01-26

Hello All I am not able to upload multiple attachments with postman and I don't understand why Here there is my Api in order to replace existing files

    [HttpPost]
    [Route("api/attachments/UpdateMultiple")]
    public Result UpdateMultiple(List<int> id) 
    {
        try
        {
           ATTACHMENT[] results = new ATTACHMENT[] { };
           int position = 0;

            foreach (int i in id)
            {
               
                var file = HttpContext.Current.Request.Files[position];
                ATTACHMENT attachment = entities.ATTACHMENT.Where(a => a.IDATTACHMENT == 
                 i).FirstOrDefault();

                byte[] fileBytes = new byte[] { };

                using (var ms = new MemoryStream())
                {
                    file.InputStream.CopyTo(ms);
                    fileBytes = ms.ToArray();
                }

                attachment.Binarydata= fileBytes;
                attachment.TypeFILE = file.ContentType;
                attachment.NAMEFILE = file.FileName;
                entities.SaveChanges();
                
                results[position] = (attachment);
                position  ;
            }
            return new Result("OK", results );
        }
        catch (Exception e)
        {
            
            return new Result("KO",    e);
        }
    }

Here Postman: enter image description here

enter image description here

Any Suggestion? I have no Idea what to do

CodePudding user response:

Try adding FromQueryAttribute/FromUriAttribute (depending on the ASP.NET version) to parameter:

public Result UpdateMultiple([FromQuery] List<int> id)

Or

public Result UpdateMultiple([FromUri] List<int> id)

UPD

ATTACHMENT[] results = new ATTACHMENT[] { }; creates an empty array, so accessing it by any index will throw an exception, change it to var results = new ATTACHMENT[id.Count];

CodePudding user response:

Solved it with help of Guru Stron -thank you!

to fix, I had to add/modify:

public Result UpdateMultiple([FromUri] List<int> id){
 List<ATTACHMENT> results = new List<ATTACHMENT>();
 int pos = 0;
 foreach (int i in id)
            {
               
                var file = HttpContext.Current.Request.Files[pos];
                pos  ;

                [...]

                results.Add(attachment);

                [...]
   }

}

  • Related