@this__all

Как правильно отравить form-data на сервер?

Подскажите как правильно отправить form-data с помощью axios во Vue

Мой код

<script>
import axios from "axios";

export default {
  metaInfo: {
    title: "Добавить сотрудника"
  },
  data: () => ({
    post: null,
    first_name: "",
    second_name: "",
    surname: "",
    file: "",
    mac: "",
    options: null,
    textModal: "",
    openModal: false
  }),
  created() {
    axios
      .get("http://localhost:8888/public/api/posts", {
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + this.$store.getters.getToken
        }
      })
      .then(response => {
        if (response.status == 200) {
          this.options = response.data.posts;
        }
      });
  },
  methods: {
    newEmployee() {
      const formData = new formData();
      formData.append("photo", this.file);
      if (
        this.post != null ||
        this.first_name != "" ||
        this.second_name != "" ||
        this.surname != "" ||
        this.file != "" ||
        this.mac != ""
      ) {
        axios
          .post(
            "http://localhost:8888/public/api/add-employee",
            {
              post: this.post,
              first_name: this.first_name,
              second_name: this.second_name,
              surname: this.surname,
              file: this.file,
              mac: this.mac,
              formData
            },
            {
              headers: {
                "Content-Type": "application/json",
                Authorization: "Bearer " + this.$store.getters.getToken
              }
            }
          )
          .then(response => {
            if (response.status == 201) {
              this.$store.commit("logout");
              this.$router.push("/");
            }
          })
          .catch(error => {
            if (error.response.status == 422) {
              this.textModal = "";
              this.openModal = true;
              setTimeout(() => (this.openModal = false), 2000);
            }
          });
      } else {
        this.textModal = "Введите все данные!";
        this.openModal = true;
        setTimeout(() => (this.openModal = false), 2000);
      }
    },
    selectPhoto() {
      this.file = this.$refs.file.files[0];
    }
  }
};
</script>
  • Вопрос задан
  • 2768 просмотров
Решения вопроса 2
@bubaley
Поменяйте Content-Type: multipart/form-data
Если есть возможность, то лучше использовать json. Перед отправкой из картинки делать base64 и на беке приводить обратно к файлу.
Ответ написан
Комментировать
mcavalon
@mcavalon
Девелопер
let form_data = new FormData();
form_data.append( 'title', app.title );
form_data.append( 'type', app.activeTab ? 'url' : 'file' );

this.axios.post('/url', form_data)....
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы