【问题标题】:send image with other attributes to post method in api将具有其他属性的图像发送到 api 中的 post 方法
【发布时间】:2020-01-30 07:36:05
【问题描述】:

我使用下面的代码将图像发送到 post 方法并将其保存为数据库中的 BLOB 并且它工作成功:

角码:

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 代码:

 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);
    }

但现在我需要发送更多带有图像的信息(类型 id、名称),而不仅仅是图像,所以角度代码将类似于:

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()
 }

发送和插入数据库的任何帮助。

【问题讨论】:

    标签: c# angular api web-services image-uploading


    【解决方案1】:

    使用 FormData 将附加信息附加到 api 调用。

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

    您可以使用多个具有相同名称的值。

    【讨论】:

      【解决方案2】:

      我想你可以只做一个上传文件的方法,然后用文件名做另一个数据插入方法,所以它会像: 公共 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);//这里你上传其他数据 console.log("从这里传过来的url",this.Url) return this.http.post(this.Url , this.img).subscribe() }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-27
        • 1970-01-01
        • 2017-12-04
        • 1970-01-01
        • 1970-01-01
        • 2020-09-29
        • 1970-01-01
        相关资源
        最近更新 更多