简体   繁体   中英

Angular 415 Unsupported Media Type

I am trying to upload an image to a folder and at the same time insert the fields into the database, however when I click the save button I get this error: 415 Unsupported media type. Does anyone know the reason?

Am I doing something wrong on the server side too?

I will present the code used in both asp net core and angular. This is the first time I'm working with this technology, possibly I must be doing something wrong:(

Class

 public Rp CreateProduct(SqlConnection conn, Product products, IFormFile file)
        {
            Rp devolve = new Rp();
            devolve = new Rp(1, "", "", "sucess");
            SqlCommand cmd = conn.CreateCommand();
            SqlTransaction transaction;     
            conn.Open();
            transaction = conn.BeginTransaction();

            try
            {               
                cmd.CommandText = "INSERT INTO[Products](Reference, Name, Description)" +
                            " Values (@Reference, @Name, @Description)";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@Reference", SqlDbType.VarChar).Value = Reference;
                        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = Name;
                        cmd.Parameters.Add("@Description", SqlDbType.VarChar).Value = Description;
                        cmd.Transaction = transaction;
                        cmd.ExecuteNonQuery();
                        transaction.Commit();
            }

            catch (Exception ex)
            {
                transaction.Rollback();
                devolve = new Rp(3, "", ex.Message, "");
            }
            finally
            {
                conn.Close();
            }
            return devolve;
        }

controller

[HttpPost]
        [Authorize]
        [Route("PostProduct")]
        public ActionResult<Rp> PostProduct([FromBody] Product p, IFormFile file, [FromQuery] string s)
        {
            try
            {

                file = Request.Form.Files[0];
                var folderName = Path.Combine("Resources", "Images");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

                if (file.Length > 0)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition)
                                    .FileName.Trim('"');
                    var fullPath = Path.Combine(pathToSave, fileName);
                    var dbPath = Path.Combine(folderName, fileName);

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }

                    return Ok(new { dbPath });
                }

                Global.Global glo = new Global.Global();
                Product prod = new Product();
                SqlConnection connection = glo.CriaConnection(configuration.GetConnectionString("BD"), s;
                Rp r = prod.CreateProduct(connection, p, file);
                return r;
            }
            catch (Exception)
            {
                return null;
            }
        }

Angular

     this.uploadService.postProduct(params).then(function (r) {
        if (r.codigo == 1) {
          notify(r.info, "success", 30);
        } else {
          notify(r.des, "error", 30);
        }
      }).catch();
    });


 postProduct(data): Promise<any> {
    let self = this;
    let urlAux = self.url + "/Products/PostProduct";

    return this.http
      .post(urlAux, data)
      .toPromise()
      .then(this.extractDataStream)
      .catch(this.handleErroPromise);
  }


constructor(private http: HttpClient) {
    this.url = localStorage.getItem("UrlS");
    this.url = this.url.replace(/"/g, "");
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      })
    }
  }
  private handleErroPromise(error: Response | any) {
    console.error(error.message || error);

    return Promise.reject(error.message || error);
  }

  private extractDataStream(res) {
    return res;
  }

try with removing 'Accept': 'application/json' in your typescript file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM