Save data and image in table

I’m trying to save information in a table, which also has a field of type … Read more Save data and image in table

I’m trying to save information in a table, which also has a field of type varbinary(max) (an image) (SQL Server)

class AddDoctor extends Component {
    state = {
      file: null,
      name: "",
      phoneNumber: "",
      email: "",
      status: "Active",
      specialty: "",
      specialities: [],
    };

    componentDidMount() {
      const URL = "http://localhost:55317/api/TSpecialties";
      ApiService.get(URL)
        .then((data) => this.setState({ specialities: data }))
        .catch((err) => console.log(err));
    }

    imgClick = () => {
      const file = document.querySelector("#id-file");
      file.click();
    };

    handleChange = (e) => {
      const state = this.state;
      state[e.target.name] = e.target.value;

      this.setState({
        ...state,
      });
    };

    handleFileChange = (event) => {
      this.setState({
        file: URL.createObjectURL(event.target.files[0]),
      });
    };

    handleSubmit = (e) => {
      e.preventDefault();
      const URL = "http://localhost:55317/api/TDoctors/";

      const DATA = {
        doctorName: this.state.name,
        doctorProfileImg: this.state.file,
        doctorPhoneNumber: this.state.phoneNumber,
        doctorEmail: this.state.email,
        doctorStatus: this.state.status,
        doctorSpecialtyId: Number(this.state.specialty),
      };

      let formData = new FormData();
      formData.append("doctorProfileImg", DATA.doctorProfileImg);
      formData.append("doctorName", DATA.doctorName);
      formData.append("doctorEmail", DATA.doctorEmail);
      formData.append("doctorPhoneNumber", DATA.doctorPhoneNumber);
      formData.append("doctorStatus", DATA.doctorStatus);
      formData.append("doctorSpecialtyId", DATA.doctorSpecialtyId);

      const options = {
        method: "POST",
        body: formData
      };

      fetch(URL, options)
      .then(res => console.log(res))
      .catch(err => console.log("ERR: " + err))
    };

    render() {
      return (
        <div>
          <form className="row g-3" onSubmit={this.handleSubmit}>
            <div className="col-md-6">
              <label htmlFor="name" className="form-label">
                Name
              </label>
              <input
                type="text"
                className="form-control"
                id="name"
                name="name"
                onChange={this.handleChange}
                placeholder="Input your name"
              />
            </div>
            <div className="col-md-6">
              <label htmlFor="email" className="form-label">
                Email
              </label>
              <input
                type="text"
                onChange={this.handleChange}
                name="email"
                className="form-control"
                id="email"
              />
            </div>
            <div className="col-md-6">
              <label className="mb-2" htmlFor="phoneNumber">
                Phone Number
              </label>
              <div className="input-group mb-2 mr-sm-2">
                <div className="input-group-prepend">
                  <div className="input-group-text">+51</div>
                </div>
                <input
                  type="text"
                  onChange={this.handleChange}
                  className="form-control"
                  id="phoneNumber"
                  name="phoneNumber"
                  placeholder="Phone Number"
                />
              </div>
            </div>
            <div className="col-md-12">
              <label htmlFor="specialty" className="form-label">
                Specialty
              </label>
              {/*    */}

              <select
                id="specialty"
                name="specialty"
                onChange={this.handleChange}
                className="form-select"
              >
                <option defaultValue>Choose...</option>
                {this.state.specialities.map((sp) => (
                  <option value={sp.specialtyId}>
                    {sp.specialtyName}
                  </option>
                ))}
              </select>

              {/*    */}
            </div>
            <div className="col-12 my-5">
              <button
                type="submit"
                className="btn btn-outline-success w-100"
              >
                Save
              </button>
            </div>
          </form>
          <div className="col mx-5" style={{ minWidth: "250px" }}>
            <img
              src={ this.state.file}
              id="img-select"
              onClick={this.imgClick}
              className="img-fluid img-thumbnail"
              alt="doctor-img"
            />
            <input
              type="file"
              style={{ display: "none" }}
              onChange={this.handleFileChange}
              id="id-file"
            />
          </div>
        </div>
    );
   }
  }

Controller POST:

// POST: api/TDoctors
    [HttpPost]
    public async Task<IActionResult> PostTDoctor([FromBody] TDoctor tDoctor)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.TDoctor.Add(tDoctor);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetTDoctor", new { id = tDoctor.DoctorId }, tDoctor);
    }

response on console developer tools when submit form:

enter image description here

and…

enter image description here

I have searched a lot of information and I cannot find the solution. I tried placing the multipart/form-data and it doesn’t work either. I hope you can help me please.

Source: JavaSript – Stack Overflow



Leave a Reply

Your email address will not be published. Required fields are marked *