0

I use the code below to send an image to post method and save it as BLOB in DB and it's working successfully:

angular code:

public postUploadedFile(file:any){

   this.formData = new FormData();
   this.formData.append('file',file,file.name);

  this.Url='http://localhost:38300/api/site/PostUploadFiles';
  console.log("url passed from here",this.Url)

  return this.http.post(this.Url , this.img).subscribe()
 }

API code:

 public IHttpActionResult PostUploadFiles()
    {
        int i = 0;
        var uploadedFileNames = new List<string>();
        string result = string.Empty;

        HttpResponseMessage response = new HttpResponseMessage();

        var httpRequest = HttpContext.Current.Request;
        if (httpRequest.Files.Count > 0)
        {

        while(i < httpRequest.Files.Count && result != "Failed")
            {


                br = new BinaryReader(httpRequest.Files[i].InputStream);
                ImageData = br.ReadBytes(httpRequest.Files[i].ContentLength);
                br.Close();
                if (DB_Operation_Obj.Upload_Image(ImageData) > 0)
                {
                    result = "success";
                }
                else
                {
                    result = "Failed";
                }
                i++;
            } 

        }
        else
        {
            result = "can't find images";
        }
        return Json(result);
    }

but now I need to send more info with image ( type id, name) not just the image, so angular code will be like :

public postUploadedFile(file:any, type_id:number,site_id:number){
  this.img = new Image_List();
  this.img.images = new Array<PreviewURL>();
  this.img.type_id= type_id;
  this.img.Reference_id = site_id;
  this.img.images.push(file);
   this.formData = new FormData();
   this.formData.append('file',file,file.name);

  this.Url='http://localhost:38300/api/site/PostUploadFiles';
  console.log("url passed from here",this.Url)

  return this.http.post(this.Url , this.img).subscribe()
 }

any help to send and insert in DB.

rabie
  • 23
  • 3

2 Answers2

0

I think you could just make a single upload file method, and make another method for data insert with the file name,so it will be like: public postUploadedFile(file:any){ this.formData = new FormData(); this.formData.append('file',file,file.name); this.Url='http://localhost:38300/api/site/PostUploadFiles'; This.newMethod(filename);//and here you upload the other data console.log("url passed from here",this.Url) return this.http.post(this.Url , this.img).subscribe() }

Mostafa Harb
  • 1,558
  • 1
  • 6
  • 12
0

Use FormData to append additional information to api call.

const formData = new FormData();
formData.append(file.name, file,'some-data');

You can use multiple values with the same name.

Richard Vinoth
  • 280
  • 3
  • 12