Axios: 'Content-Type': 'multipart/form-data'가 있는 .post를 가져올 수 없습니다.

에 만든 2016년 05월 11일  ·  99코멘트  ·  출처: axios/axios

저는 오늘 몇 시간 동안 업로드해야 하는 몇 가지 매개변수와 파일을 사용하여 게시 요청을 받으려고 노력했습니다.

순수 자바 스크립트 및 XMLHttpRequest와 함께 작동하도록 만들 수 있었지만 Axios에서는 작동하지 않습니다. 내가 뭘 잘못하고 있죠?

다음은 XMLHttpRequest를 사용하여 작동하는 코드입니다.

let data = new FormData();

data.append('action', 'ADD');
data.append('param', 0);
data.append('secondParam', 0);
data.append('file', new Blob([payload], { type: 'text/csv' }));

// this works
let request = new XMLHttpRequest();
request.open('POST', url);
request.send(data);

그 'Axios' 버전은 무엇입니까?

다음은 내 시도 중 하나입니다(간단한 시도).

// this won't work
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
    axios.post(url, data, config)
    .then(response => console.log(response))
    .catch(errors => console.log(errors));

감사합니다! 그리고 Axios와 함께 해주셔서 감사합니다!

가장 유용한 댓글

@rafaelbiten 방금 문제를 재현하려고 시도했지만 아무 소용이 없습니다. 다음 코드를 사용했습니다.

const data = new FormData();

data.append('action', 'ADD');
data.append('param', 0);
data.append('secondParam', 0);
data.append('file', new Blob(['test payload'], { type: 'text/csv' }));

axios.post('http://httpbin.org/post', data);

데이터가 서버로 성공적으로 전송되었습니다.

screen shot 2016-05-12 at 9 12 19 pm

모든 99 댓글

코드가 좋아 보입니다. (Content-Type을 설정할 필요는 없지만 중요하지 않습니다.) axios를 통해 요청을 보내려고 하면 어떻게 됩니까?

Content-Type을 설정하거나 설정하지 않아도 이 경우에는 아무 것도 변경되지 않는 것으로 나타났습니다. Axios를 사용하여 요청을 보내려고 할 때 데이터가 빈 문자열로 가는 것처럼 보이므로 백엔드는 누락된 매개변수와 관련된 오류로 응답합니다.

나는 0.9.1을 사용하고 있었지만 문제는 0.11.0에서 지속됩니다.

이 문제를 디버깅하는 데 도움이 될 수 있는 다른 작업이 있으면 알려주세요. 알겠습니다.
Tks @nickuraltsev !

Chrome 개발자 도구 네트워크 패널에서 요청이 어떻게 보이는지 살펴보고 가능한 경우 스크린샷을 제공해 주시겠습니까?

@nickuraltsev 이것이 도움이 되는지 확인하십시오:

screen shot 2016-05-11 at 2 56 12 pm

요청 헤더가 잘못된 것 같습니다.

그래서 요청 페이로드가 없습니까?

글쎄, 우리는해야하지만 데이터는 빈 문자열로갑니다. 나는 그것을 깨뜨릴 수있는 것이 무엇인지 모릅니다 (내 첫 번째 게시물에서 공유 한 코드를 고려할 때).

내가 참조. 그리고 개발자 도구에는 요청에 대한 요청 페이로드 섹션이 없습니다. 맞습니까?

관련 헤더 문제일 수 있습니다. 콘텐츠 유형이 요청의 구성 개체에 설정되면 연결됩니다.
axios.post(
'https://example.com/login',
{emailAddress: 이메일, 비밀번호: hashedPassword},
{헤더: {'콘텐츠 유형': '애플리케이션/json'}}
);

헤더 콘텐츠 유형은 application/json,application/json으로 제공됩니다.
이 경우 본문은 구문 분석되지 않습니다.

@nickuraltsev 맞아! 저 스크린샷에 보이는 것은 제가 개발 도구에 대해 가지고 있는 전부입니다.
@rrapant 가 맞을 수도 있지만 'Content-Type' 설정 여부는 적어도 이 경우에는 아무 것도 변경되지 않았다고 거의 확신합니다. 확실히 하려면 다시 확인을 해봐야겠네요.

@rrapant 콘텐츠 유형 값이 중복되는 문제는 #317로 수정되었습니다. 수정 사항은 다음 릴리스에 포함될 예정입니다. 감사합니다!

@rafaelbiten 방금 문제를 재현하려고 시도했지만 아무 소용이 없습니다. 다음 코드를 사용했습니다.

const data = new FormData();

data.append('action', 'ADD');
data.append('param', 0);
data.append('secondParam', 0);
data.append('file', new Blob(['test payload'], { type: 'text/csv' }));

axios.post('http://httpbin.org/post', data);

데이터가 서버로 성공적으로 전송되었습니다.

screen shot 2016-05-12 at 9 12 19 pm

@rafaelbiten 내 코드 조각에서와 같이 FromData를 사용하여 http://httpbin.org/post 로 요청을 보내 주시겠습니까?

지금은 닫습니다. 필요하면 다시 열어주세요.

안녕하세요 @nickuraltsev , 동일한 문제가 발생합니다.

      var fd = new FormData();
      fd.append('file', this.refs.multipartfiles.files[0]);

            const config = { headers: { 'Content-Type': 'multipart/form-data' } };
            axios.post('/dataAPI/sendFile', {
                "UploadCommand": fd
              }, config)
              .then(function (response) {
                console.log(response);
              })
              .catch(function (error) {
                console.log(error);
              });

아래에서 내 헤더 정보의 스크린 샷을 찾으십시오.

image

질문이 있습니다. _xios는 다중 부분 데이터 파일을 노드 서버로 보내는 것을 지원합니까?_

@Sreekhar 작동하는지 모르겠지만 FormData를 다른 개체에 래핑하는 대신 두 번째 인수로 추가할 수 있습니까?
axios.post('/dataAPI/sendFile', fd, config)

파일이 있는 부분의 이름으로 'UploadCommand'를 사용해야 하는 경우 이것을 사용해야 합니다.
fd.append('UploadCommand', this.refs.multipartfiles.files[0]);

@yungpanda 그 대안을 찾았습니다. 이제 API를 다시 만들어야 할 것 같습니다. 어쨌든 작동하는지 확인하고 스레드를 업데이트하도록 하겠습니다. 답장을 보내 주셔서 감사합니다.

@Sreekhar 브라우저가 multipart/form-data로 변경하고 경계를 자동으로 추가할 수 있도록 Content-Type을 undefined로 설정하십시오.

@nickuraltsev 이것은 노드에서 작동하지 않는 최소한의 예입니다:

const data = new FormData();

data.append('action', 'ADD');
data.append('param', 0);
data.append('secondParam', 0);

axios.post('http://httpbin.org/post', data).then(req => {
  console.log('Req done: ', req)
}).catch(err => {
  console.error('Error: ', err)
})

오류: 종료 후 쓰기

@krzkaczor axios 로 multipart/form-data를 보내는 방법을 찾았습니까?

@PierreCavalet 아니요 , 대신 request-promise 를 사용했습니다.

@krzkaczor 감사합니다, 너무 전환해야합니다

@krzkaczor 아직 수행하지 않은 경우 콘텐츠 유형을 추가해 보십시오.

const config = { headers: { 'Content-Type': 'multipart/form-data' } };
let fd = new FormData();
fd.append('file',files[0])
return axios.post("http://localhost:5000/upload", fd, config)

@krzkaczor 저도 axios 및 multipart/form-data와 동일한 문제에 직면하고 있습니다. request-promise에 사용한 코드의 요지를 게시할 수 있습니까?

@dan-boa here u go: https://gist.github.com/krzkaczor/bdbe09d4096b051a3c18387c4ca79a06 또한 문자열을 파일로 보내는 방법(경로 설정)을 보여줍니다.

궁금한 사람이 있으면 axios FormData 를 사용하는 방법의 예가 있습니다. 기본적으로 데이터를 버퍼로 스트리밍하고 올바른 헤더를 전달해야 합니다.

const concat = require("concat-stream")
const fd = new FormData()

fd.append("hello", "world")
fd.append("file", fs.createReadStream(file))
fd.pipe(concat(data => {
  axios.post("/hello", data, {
    headers: fd.getHeaders()
  })
}))

동일한 문제가 있었습니다(노드가 아닌 브라우저에서). Content-Type 헤더를 전혀 설정하지 않고 axios가 상황을 파악하도록 하면 작동하는 것으로 나타났습니다(axios 인터셉터에서도 해당 헤더를 기본값으로 설정하지 않았는지 확인하십시오. 필요한 경우 일부 나머지 API 호출에 대한 기본값인 경우 FormData() 요청에 대해 별도의 axios 인스턴스를 만들 수 있습니다.

다른 원격 서버에 업로드하려고 할 때 노드 측에서 request-promise를 사용하게 되었습니다.

같은 이유로 request-promise로 전환했습니다. 그렇지 않으면 axios를 사랑하십시오!

@guncha 귀하의 예제는 UTF8로 인코딩된 바이너리 파일을 업로드할 때까지 0.15.3에서 저에게 효과적이었습니다. 버퍼를 사용하도록 concat에 지시하면 문제가 해결되었습니다.

const concat = require("concat-stream")
const fd = new FormData()

fd.append("hello", "world")
fd.append("file", fs.createReadStream(binaryFile))
fd.pipe(concat({encoding: 'buffer'}, data => {
  axios.post("/hello", data, {
    headers: fd.getHeaders()
  })
}))

또는 약속을 사용합니다.

const promise = new Promise((resolve) => {
  const fd = new FormData();
  fd.append("hello", "world");
  fd.append("file", fs.createReadStream(binaryFile));
  fd.pipe(concat({ encoding: 'buffer' }, data => resolve({ data, headers: fd.getHeaders() })));
});
promise.then(({ data, headers }) => axios.post('/hello', data, { headers }));
const callApi = (url, params) => {
  const formData  = new FormData()
  for(let name in params) {
    let param = params[name]
    if (typeof param === 'object') {
      param = JSON.stringify(params[name])
    }
    formData.append(name, param)
  }

  return axios.post(url, formData)
    .then(response => {
      console.log(response)
    })
}

@guncha 가 나를 위해 일하고 있습니다. 감사 해요

여기 같은 문제

Content-Type 에 경계를 추가하기만 하면 됩니다.

const request = require('axios');
const FormData = require('form-data');
const fs = require('fs');

let data = new FormData();
data.append('file1', fs.createReadStream('./image1.jpeg'), 'image1.jpeg');
data.append('file2', fs.createReadStream('./image2.jpeg'), 'image2.jpeg');

let options = {
    method: 'POST',
    url: 'http://localhost:3200/upload',
    headers: {
        'Content-Type': `multipart/form-data; boundary=${data._boundary}`
    },
    data
};

return request(options)
    .then(response => {
        console.log(response);
    });

야,
이 파일을 json 형식으로 가져왔습니다. 누구든지 이 파일을 멀티파트 파일로 변환하는 방법을 도와줄 수 있습니다.
사용 플랫폼은 java8입니다.
"body": "------WebKitFormBoundaryQsJGeBuR8e9dQ4Pm\r\nContent-Disposition: form-data; name=\"file\"; filename=\"backup prolog.txt\"\r\nContent-Type: text/plain\r\n\r\n%All the Pre-Defined relations\r\nconnected(hira,rohit,father).\r\nconnected(rohit,rakesh,father).\r\nconnected(ram,hira,father).\r\nconnected(kavri,hira,mother).\r\nconnected(hira,kavri,son).\r\nconnected(arun,vinayak,father).\r\nconnected(vinayak,arun,son).\r\nconnected(arun,shashi,husband).\r\nconnected(shashi,arun,wife).\r\nconnected(vinayak,vardaan,brother).\r\nconnected(vardaan,vinayak,brother).\r\nconnected(shashi,vinayak,mother).\r\nconnected(vinayak,shashi,son).\r\n\r\n\r\n\r\nconnected2(X,Y,D) :- connected(X,Y,D).\r\n%connected2(X,Y,D) :- connected(Y,X,D).\r\n\r\nnext_node(Current, Next,R, Path) :-connected2(Current, Next, R),not(member(Next, Path)).\r\n\r\nfunc(how,is,X,related,to,Y):-depth_first(X,Y,[X],P),write(P).\r\n%Procedure to Start the depth_first\r\ndepth_first(Goal, Goal, _, [Goal]).\r\n\r\ndepth_first(Start, Goal, Visited, [Start,is,R,of|Path]) :-next_node(Start, Next_node,R, Visited),depth_first(Next_node, Goal,[Next_node,R|Visited], Path).\r\n\r\n\r\n\r\n\r\n\r\n\r\n------WebKitFormBoundaryQsJGeBuR8e9dQ4Pm--\r\n"
감사

코드는 브라우저에서 작동하지만 노드에서는 작동하지 않습니다.

const fdata = new FormData();
fdata.append('user', u);
fdata.append('hostnames', n.join(' '));
const host = localStorage.getItem('host');
const port = localStorage.getItem('port');
axios({
  url: `http://${host}:${port}/hosts/remove`,
  method: 'post',
  data: fdata
}).then(response => {
  if (response.status === 200) {
    console.log(response.data);
    console.log('Removed host successfully');
  }
  return null;
}).catch(er => console.log(er));

안녕하세요 @Sreekhar
나를 위해 구성을 다음으로 변경했습니다.
const config = { headers: { 'Content-Type': 'application/json' } };
그리고 그것은 잘 작동했다

이에 대한 일관된 답변/워크플로가 있을 때까지 다시 열어주세요. 많은 사람들이 여전히 이것으로 문제를 겪고 있는 것 같습니다.

+1 재개방

바이너리 파일 데이터를 포함하는 HTTP 게시물은 axios v0.16.2에서 제대로 작동하는 것 같습니다.

// The following was tested successfully with axios v0.16.2

// Create a new form.  Note:  could also specify an existing form as
// the parameter to the FormData() constructor to copy all the elements
// from the existing form to the new one being created.

var tempFormData = new FormData();

var someNoteValue = 'Hello World';
var someAudioData = [];  // populate this with data from file, with MediaRecorder() etc.


// Add form fields

tempFormData.set('SomeNote', 'Hello World');
tempFormData.set('SomeRecording', someAudioData[0], 'SampleRecording.webm');


// Optional:  output list of form fields to the console for debugging

for (var pair of tempFormData.entries()) {
    console.log('Form field: ' + pair[0] + ', ' + pair[1]);
}


// Call Axios to post the form to myurl

axios({
    method: 'post',
    url: 'myurl',
    data: tempFormData,
    config: { headers: {'Content-Type': 'multipart/form-data' }}
})
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });

            }

또한 버퍼를 사용하여 파일을 나타낼 때 이것은 저에게 효과적이었습니다.

      const form = new FormData();
      const fileBuffer = new Buffer(
        'MM2 - noticeably shallower than the original - score: 101%', 'utf-8'
      );
      form.append('name', 'reviews.txt'); // additional form data field
      form.append('file', fileBuffer, 'original-file-name.bar');

      const res = await axios.post(`/uploadfile`, form, { headers: form.getHeaders() });

참고 사항: Axios 인스턴스의 기본값에 기본 데이터 매개변수가 설정되어 있으면 위의 솔루션 중 어느 것도 작동하지 않습니다 . Axios 인스턴스에서 기본 Content-Type 헤더를 지정했는지 확인할 수도 있습니다(axios.defaults.headers 및 axios.defaults.parameters를 통해).

이것은 적절하지 않을 수 있지만 문제는 서버 측에서 body-parser 를 사용하는 것과 관련이 있을 수 있습니다. 나는 비슷한 문제로 어려움을 겪고 있었고이 게시물을 보았습니다.

https://philna.sh/blog/2016/06/13/the-surprise-multipart-form-data/

TL;DR - body-parser 는 multipart/form-data를 처리하지 않습니다. 즉, axios 가 문제가 아니고 body-parser 가 문제입니다. 이것이 위에서 언급한 버퍼 솔루션이 작동하는 이유일 수 있습니다.

나는 이 기능이 다음과 같이 보안상의 이유로 있다고 가정합니다.

http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html

나는 그것이 누군가를 돕기를 바랍니다!

같은 문제가 있습니다. Axios 0.16.2 를 사용하고 XMLHttpRequest 로 보내는 것은 작동하지만 Axios에서는 작동하지 않습니다.

기본 FormData 개체가 있습니다.

const formData = 새로운 FormData();
formData.append('이름', '텍스트 이름');

@Janekk 의 제안을 시도했습니다.

axios({
      method: 'post',
      url,
      withCredentials: true,
      data: { formData },
    })

그런 다음 @faalkhah 의 제안:

const config = { headers: { 'Content-Type': 'application/json' } };
    axios({
      method: 'post',
      url,
      withCredentials: true,
      data: { formData },
      config,
    })

또는 @askona 의 제안:

const config = { headers: { 'Content-Type': undefined } };
    axios({
      method: 'post',
      url,
      withCredentials: true,
      data: { formData },
      config,
    })

요청 헤더는 application/json 이고 formData 은 비어 있습니다.

백엔드 https://stackoverflow.com/a/13454425/968379 에서만 작동하는 것처럼 보이기 때문에 @demeter-macik 수정을 시도하는 방법을 모르겠습니다.

안녕 모두,
나는 같은 문제를 가지고있다
클라이언트의 내 코드
`

    const url = '/file/uploadTest';
    const formData = new FormData();
    formData.append('file', file);
    formData.append('params1', value);
    formData.append('params2', value2)

    const config = {
        headers: {
            'Content-Type': 'multipart/form-data',
        }
    }
    axios.post(url,formData,config)`

sails 서버에서 콘솔 req.body를 기록합니다.
나는 요청을 10 번 호출 할 때 서버가 본문을 수신하지 못하는 약 3 4 번 (본문이 비어 있음)을 발견했습니다.
나는 크롬의 devtool을 체크인했고 요청은 여전히 ​​페이로드의 파일과 본문을 전송했습니다.
아직 이유를 찾지 못했지만 해결 방법이 있습니다.

그것은 요청 헤더입니다.

`코드

    const url = '/file/uploadTest';
    const formData = new FormData();
    formData.append('file', file);
    formData.append('params1', value);
    formData.append('params2', value2)
    const config = {
        headers: {
            'Content-Type': 'multipart/form-data',
            'params1': value,
            'params2': value2
        }
    }
    axios.post(url,formData,config)`

안녕하세요 @Sreekhar ,
문제를 해결하셨나요? 누군가가 나를 도울 수 있는 솔루션을 찾지 못했습니다. 제발.
또한 미리 감사드립니다.

안녕하세요,

multiformdata를 게시하려고 했습니다(Eztext SMS API입니다).
node.js와 함께 axios를 사용합니다.

다음 코드에 잘 작동합니다.
return new Promise(function(resolve, reject) {

        var request = require("request");
        var options = {
            method: 'POST',
            url: 'https://app.eztexting.com/sending/messages',
            qs: {format: 'json'},
            formData:
                {
                    User: '**',
                    Password: '**',
                    'PhoneNumbers[0]': '8572222***',
                    Message: 'Appointment Reminder',
                    MessageTypeID: '1'
                }
        };
        request(options, function (error, response, body) {
            if (error) {
                console.log(error);
                reject(error);
            }
            else {
                console.log(response);
                resolve(response);
            }

            // console.log(body);
        });

그러나 SMS가 전송되지 않기 때문에 axios에서는 작동하지 않지만 다음 요청에 대해 상태 코드가 200으로 표시됩니다.
var axios=require('액시오스');

         axios.post('https://app.eztexting.com/sending/messages', {
             qs: { format: 'json' },
             headers: {
                 'Content-Type': 'application/x-www-form-urlencoded'
             },
             formData:
                 { User: '****',
                     Password: '2sH****5',
                     'PhoneNumbers[0]':'85722******',
                     Message: 'Hello Yahska',
                     MessageTypeID: 1 }
         })
             .then(function (response) {
                 console.log(response);
             })
             .catch(function (error) {
                 console.log(error);
             });

포스트 요청이 Axios가 아닌 '요청' 라이브러리에서 성공하는 이유는 무엇입니까?

헤더를 설정하지 않고 JSON에서 FormData로 데이터를 변환해 보셨습니까?
데이터 헤더(예: 인증 헤더 제외)는 자동으로 처리되어야 합니다.

async function sendMessage(myJSONPayload){
  try{
    const data = convertJSON2FormData(myJSONPayload);

    const response = await axios.post('https://app.eztexting.com/sending/messages', {
  data
});
    console.log(response);
  } catch(ex){
    console error(err);
  }
}

sendMessage ({ User: '****',
                     Password: '2sH****5',
                     'PhoneNumbers[0]':'85722******',
                     Message: 'Hello Yahska',
                     MessageTypeID: 1 }
         });

JSON에서 FormData로 변환하려면 이 답변 과 같은 것을 사용하십시오.

중첩된 키는 다루기 어렵다는 것을 기억하십시오. 예를 들어 데이터를 백엔드로 보낼 때 다음과 같이 평면화하면 작동합니다.

{a: {b: 2}} --> formData.append("a.b",2)

여기에 같은 문제가 있습니다.

물론, @michaelscheurer! 요청 헤더를 설정하는 것만으로는 충분하지 않습니다. 작동하려면 FormData를 제출해야 합니다. 요청과 함께 작동하기 위해 모든 적절한 경계로 직렬화되는 브라우저 객체입니다. axios나 바닐라 js도 JSON 데이터를 FormData로 변환하지 않습니다. Axios는 FormData임을 인식하고 헤더도 설정하므로 실제로 설정할 필요가 없습니다.
이전 답변 힌트를 따르십시오 ...

@Iamuertepeluda
나는 ur 제안에 따라 다음을 시도했지만 운이 없었습니다. 상태 200 확인과 동일한 동작이지만 다음 요청으로 SMS가 전송되지 않습니다.
var axios=require('액시오스');

    const FormData = require('form-data');

    const form = new FormData();

    //fo this jason I created a form
    // formData:
    // {
    //     User: '*****',
    //         Password
    // :
    //     '******',
    //         'PhoneNumbers[0]'
    // :
    //     '8****2763',
    //         Message
    // :
    //     'Appointment Reminder',
    //         MessageTypeID
    // :
    //     '1'
    // }

    form.append('User','****');
    form.append('Password','*****');
    form.append('PhoneNumbers[0]','*****');
    form.append('Message','Appointment Reminder');
    form.append('MessageTypeID','1');


         axios.post('https://app.eztexting.com/sending/messages', form,
    {
        qs: {format: 'json'},
        headers:
        {
                'content-type'
        :
            'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
        }
    }
)
             .then(function (response) {
                 console.log(response);
             })
             .catch(function (error) {
                 console.log(error);
             });

@Ruchi2729 node.js 또는 브라우저를 사용하고 있습니까?

브라우저에서는 FormData가 기본이므로 const FormData = require('form-data'); 가 필요하지 않습니다.

또한 헤더와 q를 설정하지 않고 시도하거나 시도하십시오.

axios.request({
 url: "https://app.eztexting.com/sending/messages"
 type: "post",
 data: form //the instance of FormData of your stub
});

내가 언급했듯이 브라우저에서 자동으로 헤더를 설정해야 합니다.

@Ruchi2729 노드를 사용하고 있는 것 같습니다. 죄송합니다.
form-data 를 axios와 함께 한 번 사용한 것을 기억하지만 실제로 작동했는지는 기억나지 않습니다.

하지만 이것이 eztexting으로 SMS를 보내는 올바른 방법이라고 확신하십니까? 그들의 문서에서는 API 키와 자체 노드 클라이언트를 사용해야 하는 것처럼 다르게 보입니다...

이것을 다시 열 수 있습니까? 저를 포함해 아직도 많은 분들이 이 문제에 대해 고민하고 계시는 것 같습니다. 예를 들어 이 요청은 axios를 통해 예상대로 서버에 전달되지 않지만 Postman을 통해 multipart/form-data 같은 파일을 보내면 모두 작동합니다.

screen shot 2018-03-26 at 12 22 35 am

편집: 내 문제는 base64로 인코딩된 데이터 URI를 양식 데이터로 보내려고 했습니다. 다른 사람이 동일한 문제로 어려움을 겪고 있다면 다음은 이를 변환하는 몇 가지 샘플 코드입니다.

async function importCsv(data: CsvImportData): Promise<void> {
    const formData = new FormData();
    const headers = {'Content-Type': 'multipart/form-data'};

    formData.append('csv', dataURItoFile(data.file, `upload_${Date.now()}.csv`));

    try {
      await axios.post('https://example.com/api/upload/csv', formData, {headers});
    } catch(e) {
      console.error(e);
    }
}

function dataURItoFile(dataURI: string, defaultFileName: string): File {
  let byteString: string;
  const [metadata, data] = dataURI.split(',');
  if (/base64$/.test(metadata)) {
    byteString = atob(data);
  } else {
    byteString = unescape(data);
  }

  const mimetype: string = metadata.split(':')[1].split(';')[0];
  const filename: string = (metadata.match(/name\=(.*);/) || [])[1] || defaultFileName;

  let dataView: Uint8Array = new Uint8Array(byteString.length);
  for (let i = 0; i < byteString.length; i++) {
    dataView[i] = byteString.charCodeAt(i);
  }
  return new File([dataView], filename);
}

안녕하세요 이 문서를 참조하고 있습니다 :- https://www.eztexting.com/developers/sms-api-documentation/rest#Sending
API 키 및 모든 문서에 대해 어떤 문서를 참조하고 있습니까?

@루치2729
다른 SMS 서비스이며 노드에 대한 자체 클라이언트가 있는 Nexmo 와 혼동해서 죄송합니다 😅

그러나 어쨌든 참조한 문서 에 따르면 formatjson 로 설정하고 axios가 JSON 페이로드를 보내도록 하여 FormData를 피할 수 있습니다(페이로드 형식으로 암시적으로 헤더를 추측할 수 있음)

https://app.eztexting.com/sending/messages?format=json

나는 인정하고 싶은 이 문제로 더 오래 고생했고 이것이 누군가에게 도움이 되기를 바랍니다. axios, express 및 express-fileupload를 사용하고 있습니다. FormData에 추가한 매개변수를 사용하여 Node에 성공적으로 업로드할 수 있습니다. req.files로 파일을 선택하고 req.body['yourfilename']로 나머지 양식 데이터를 선택합니다.

서버(익스프레스):

screen shot 2018-03-27 at 1 59 08 pm

router.post('/helper/amazon/upload', function(req, res) { if (!req.files) { return res.status(400).send('No files were uploaded.') } console.log(req.body.filename); return console.log(req.files);

프런트 엔드(axios)

screen shot 2018-03-27 at 1 58 45 pm

const formData = new FormData(); formData.append('file', this.validFile); formData.append('filename', 'trails/' + this.$route.params.id.split('-')[0] + '/camping/'); axios.post( /api/helper/amazon/업로드 , formData, { headers: { 'Content-Type': 'multipart/form-data' } });

결과:

screen shot 2018-03-27 at 2 02 11 pm

동일한 문제가 있습니다. 내 개발 도구를 사용하여 파일 데이터를 성공적으로 보냈지만 내 컨트롤러 내부에서 내 $request->file('file')이 비어 있음을 알 수 있습니다.
내 구성 요소

제출양식() {
this.formData = 새로운 FormData();
this.formData.append('파일', this.$refs.file.files[0]);
this.formData.append('분석', this.analyticsForm.analysis);
this.formData.append('_method','PATCH');
axios.post('/분석',
this.formData
,{헤더: {'콘텐츠 유형': 'multipart/form-data'}}).then(응답 => this.isSubmittedRedirect(false,'/sources/'+this.source+'/description'+'') )
.catch((오류) => console.log(오류))
},

Content-Type을 multipart/form-data 로 지정해야 하기 때문에 MVC가 그런 식으로 얻는 것을 좋아하지 않는 것 같기 때문에 FormData로 무엇이든 하는 것이 문제라는 것을 발견했습니다. Microsoft 사이트에서 다음과 같이 if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } 확인하십시오. https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part- 2

내 파일을 base64 문자열로 가져오는 것이 더 낫습니다.
https://stackoverflow.com/questions/37134433/convert-input-file-to-byte-array/49676679#49676679

이 예에서 DropZone을 사용했기 때문에 이 게시물은 이를 수행하는 방법과 더 관련이 있을 수 있습니다.
https://stackoverflow.com/questions/32556664/getting-byte-array-through-input-type-file/49660172#49660172

그리고 여기에 대해 자세히 설명합니다. https://stackoverflow.com/questions/47574218/converting-from-blob-to-binary-to-save-it-to-mongodb/49660839#49660839

그런 다음 JSON 개체를 만들 수 있습니다.

const myObj = {
   file = myBase64String,
   title = "myfileTitle.jpg"`
   type = "image/jpeg"`
}

axios를 사용하는 대신 XMLHttpRequest를 사용했습니다.

 const xhr = new XMLHttpRequest();

헤더를 열고 설정하십시오.

 xhr.open('POST', '/api/FileUpload/Post', true);
 xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8' );
 xhr.withCredentials = true;

응답을 캡처하기 위해 onreadystatechange 를 설정했습니다.

xhr.onreadystatechange = (response) =>
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(response.target.responseText);
    }
}

그리고 보내기:

 xhr.send(JSON.stringify(myObj));

axios를 사용한다면 아마도 다음과 같을 것입니다:

try {
    var axios = require('axios');
    const config = {
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
        }
    }
    await axios.post('https://example.com/api/upload/post', myObj, config)
        .then(function (response) {
             console.log(response);
         })
         .catch(function (error) {
             console.log(error);
         });
}
catch(e) { console.log(e); }

MVC 측에서는 일치하는 모델이 필요합니다.

public class MyModel {
    public string file { get; set; }
    public string title { get; set; }
    public string type { get; set; }
}

그런 다음 [FromBody] 태그를 사용하여 Post 호출의 매개변수로 사용합니다.

[System.Web.Http.HttpPost]
public virtual JsonResult<string> Post([FromBody]MyModel myModelObject)
{
    string strBase64FileString = myModelObject.file;
    string strTitle = myModelObject.title;
    string strFileType = myModelObject.type;

    return Json(JsonConvert.SerializeObject(new { file = myModelObject.file, title = myModelObject.title, myModelObject.type }));
}

당신은 당신이 보낸 것을 돌려 받아야합니다. 이것을 테스트로 구현하는 경우 매우 작은 파일로 수행하여 시스템의 브라우저/메모리가 잠길 가능성이 있는 영원히 기다리지 않도록 하십시오.

@navyjax2
나는 당신이 말한대로하고 있었고 작은 파일로 작동했지만 큰 파일 (> 250Mo)을 보내야하고 네 브라우저를 잠그고있었습니다.

예, 이를 위해 파일 배열을 관리 가능한 크기의 덩어리로 나누고 블록으로 보낼 수 있습니다. 다른 쪽(서버 측) 끝에는 이를 다시 결합할 수 있는 메서드가 있고 매개변수를 제공하여 그렇게 할 수 있습니다. 어떤 청크(첫 번째, 두 번째, 세 번째 등)인지 그리고 서버 측에서 파일을 처리하기 전에 예상되는 총 청크 수를 알고 있습니다. 하지만 그 크기의 파일로 무엇을 하든, 제 생각에는 제대로 작동할 때까지 기다려야 할 것입니다. 청크 방식으로 수행하는 경우에도 메모리 관리에 주의해야 합니다. 매번 동일한 변수의 새 버전을 다시 인스턴스화하지 않고 매번 변수를 지우거나 재사용해야 하기 때문입니다. 당신은 블록을합니다. 전역 변수가 좋은 몇 번 중 하나입니다. 또는 실행할 때마다 모델 필드로 설정됩니다.

@epferrari 에 동의합니다. 이 문제를 다시 여는 것을 고려하십시오.
Chrome에서 FormData와 함께 base64 문자열을 보내는 것은 괜찮지만 node(v8.9.3)에서 axios로 완료할 수 없습니다.
그리고 그것은 node-fetch와 함께 작동합니다 ...

const fetch = require('node-fetch')
const axios = require('axios')
const FormData = require('form-data')
const base64Img = require('base64-img')

const b64 = base64Img.base64Sync('./test.jpg').split('base64,')[1]
const form = new FormData()
form.append('b64_data', b64)
const headers = form.getHeaders()

// with node-fetch it worked
fetch('http://some.url', {
  method: 'POST',
  body: form,
  headers,
}).then(res => res.text()).then(console.log).catch(console.log)

// not working with axios
axios({
  method: 'POST',
  url: 'http://some.url',
  data: form,
  headers,
}).then(console.log).catch(console.log)

=== 업데이트 ===
이해할 수 없습니다. node-fetch 및 axios에 동일한 헤더를 사용하고 동일한 양식 데이터를 서버에 게시하는 것 같습니다. 어떻게 다르게 끝나나요?
그건 그렇고, 내가 게시하는 실제 URL은 here 에서 왔으며, 내가하고있는 일은 nodejs를 사용하여 브라우저의 http 요청을 조롱하여 이미지를 서버에 보내고 링크를 다시 가져 오는 것입니다.

다음을 사용하여 이 문제를 해결했습니다.

<input onChange="emitImageInfo(this)" type="file" multiple>

function emitImageInfo($event){
  let files = $event.target.files
  let formData = new FormData();

  for (let i = 0; i < files.length; i++)
      formData.append('image[' + i + ']', files[i])

  axios.post('file/upload', formData)
     .then((result) => { console.log('got it') })
     .catch((err) => { console.log(err) })
}

이것은 효과가 있었다:

axios.post(localhost:3000/items, formData, { 헤더: { '콘텐츠 유형': '멀티파트/양식 데이터' }});

나는 같은 문제를 가지고있다

golang과 함께 작동하지 않음

Vue에서 간단한 방법을 찾아보지만, 다른 상황에서도 활용될 수 있을 것 같아요.😀
백엔드: Express.js 및 express-fileupload 패키지.

<template>
  <div>
    <input type="file"
           name=""
           id="file-upload"
           multiple
           @change="filesChange($event.target.files)">
    <button @click="handleSubmit">Send</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formData: new FormData(),
    };
  },
  methods: {
    filesChange(fileList) {
      // First: append file to FormData
      Array.from(Array(fileList.length).keys()).map(x => {
        this.formData.append(fileList[x].name, fileList[x]);
      });
    },
    handleSubmit() {
      // Append Text
      this.formData.append('username', 'Jeremy');

      // Append Number: Will be string
      this.formData.append('number', 9527);

      // Append Array: Need to be converted to a string
      this.formData.append('arrData', JSON.stringify([1, 2, 3]));

      // Append Array: Need to be converted to a string
      this.formData.append(
        'objData',
        JSON.stringify({ name: 'Jeremy', age: 28 })
      );

      this.axios({
        method: 'post',
        url: `file/multi-users`,
        data: this.formData,
      }).then(res => {
        console.log(res);
      });
    },
  },
};
</script>

capture

우리도 같은 문제에 직면했습니다. 콘텐츠 유형 헤더가 반응 자바 스크립트에서 제거된 다음 제대로 작동했습니다. 이전에는 콘텐츠 유형에서 명시적으로 설정할 때 경계가 설정되지 않았습니다.

편집: 그것에 대해 더 읽은 후 Express가 제 문제인 것 같습니다. 바라건대 이것은 다른 사람들에게 유용 할 수 있습니다

동일한 문제가 여기에 있습니다. @nickuraltsev 문제를 다시 열 것을 적극 권장합니다.

다음 코드를 사용하여 axios를 통해 노드 서버에 파일을 게시하려고 합니다.

let ff = new FileReader();
ff.onload = (ev) => {
      var result = ev.target.result;
      console.log(`result: ${result} of type ${typeof(result)}`);
      axios.post('/test', {
                 file: result
                 })
                 .then((response) => {
                         console.log(`Response: ${response}`)
                  })
                  .catch((err) => {
                        console.log(`Test error: ${err}`);
                   })
}

var sampleFile = //getting the file here
ff.readAsArrayBuffer(sampleFile);

요청 본문은 서버 측에서 완전히 비어 있습니다.

파일을 직접 보내려고 하고 파일을 ArrayBuffer로 읽고 파일을 텍스트로 읽으려고 했지만(페이로드가 너무 큼) 3가지 모두 작동하지 않았습니다.

2년 후:
같은 문제...

@demeter-macik 감사합니다. 경계를 추가하면 저에게 효과적입니다. 스마일:

    const form = new FormData();
    form.append('email', '[email protected]');
    form.append('phone_no', '63');
    form.append('phone_code', '9179303100');

    if (logo) {
      form.append('logo', logo);
    }

    const response = await axios({
      method: 'post',
      url: `${apiUrl}users`,
      data: form,
      headers: {
        'content-type': `multipart/form-data; boundary=${form._boundary}`,
      },
    });

이것은 Safari iOS를 포함한 모든 브라우저에서 확실히 작동합니다.

내 코드는 다음과 같습니다.

함수 samplePost(구성) {

// save reference this

let that = this;



// can optionally pull in form fields from an existing HTML form)

let myForm = document.getElementById('myForm');

let myFormData = new FormData(myForm);



// add in data from config.data if applicable

if (config && config.data) {

    that.objToStr(config.data, '', myFormData);



    for (let n2 in config.data) {

        if (config.data.hasOwnProperty(n2)) {

            myFormData.set(n2, config.data[n2]);

        }

    }

}



if (config.binaryFiles && config.binaryFiles.length > 0) {



    for (let i = 0; i < config.binaryFiles.length; i = i + 1) {

        let thisFile = config.binaryFiles[i];

        myFormData.append(thisFile.fieldName, thisFile.binaryData, thisFile.fileName)

    }

}





let axiosConfig = {

    method: 'post',

    url: config.url,

    data: myFormData,



    onUploadProgress: config.onUploadProgress,

};



if (config && config.binaryFiles && config.binaryFiles.length > 0) {

    axiosConfig.headers = {'Content-Type': 'multipart/form-data'};

}

else {

    axiosConfig.headers = {'Content-Type': 'application/x-www-form-urlencoded'};

}



const ax = axios.create();

// note that passing in config to the constructor is broken as of axios v0.19.0-beta.1

// So we work around by passing in config to the request() method



ax.request(axiosConfig)

    .then(function (response) {

        // handle success



        alert(response.data);



    })

};

// samplePost를 호출하여 업로드

샘플 포스트({

url: 'async',

data: {somefield: 'some value'}, //note: passes in as form fields



// optionally include array of binary files

binaryFiles: thisFileList

});

보낸 사람: Antonio Vázquez [email protected]
보낸 날짜: 2018년 9월 11일 화요일 오전 11:23
받는 사람: axios/ axios [email protected]
참조: DavidRueter [email protected] ; 댓글 [email protected]
제목: Re: [axios/axios] 'Content-Type': 'multipart/form-data'가 있는 .post를 가져올 수 없습니다. (#318)

Safari에서 게시물 요청을 하는 데 4시간이 소요됩니다. 그래도 안되는데...대체 뭐야??

여기에있는 솔루션 중 어느 것도 저에게서 효과가 없었습니다 ... :(


당신이 댓글을 달았기 때문에 이것을 받는 것입니다.
이 이메일에 직접 답장하거나 GitHub https://github.com/axios/axios/issues/318#issuecomment-420371510 에서 확인하거나 https://github.com/notifications/unsubscribe-auth/AFbi6JQBv06LTwL4z3HIAlvXAXDyps1- 스레드를 음소거하세요. https://github.com/notifications/beacon/AFbi6BSPfwPvNaWPFSdvtLKRYXS1m4uKks5uZ_9wgaJpZM4Ibm_z.gif

이것은 나를 위해 일했습니다. 감사 합니다 @arvi

twiliosms = 비동기(Codigo) => {

var FormData = require('양식 데이터');
var fs = 요구('fs');

var 형식 = 새로운 FormData();
form.append('받는 사람', '+524772773737');
form.append('보낸사람', '+737373737');
form.append('본문', Codigo);

노력하다 {
let axapi = await axios(
{
URL: '2010-04-01/계정/AC8aa53c907943af79234414bb725c2cd3/Messages.json',
baseURL: 'https://api.twilio.com',
헤더: {'콘텐츠 유형': multipart/form-data; boundary=${form._boundary} ,},
데이터: 양식,
인증: {
사용자 이름: 'AC8aa53c907943af79234414bb725c2cd3',
비밀번호: * ,
},
방법: '게시',
}
)

} catch(e) {console.error(e)}
}

이 라이브러리를 방황하고 있습니다. 여전히 양식 데이터 게시물에 대한 자체 작성 해결 방법이 필요합니다....

모든 업데이트?

NodeJS 10.11.0 및 Axios 0.18.0에서 유사한 오류가 있습니다(#1892 참조). @arvi 의 수정을 시도했지만 작동하지 않습니다.

나를 위해 이것은 작동합니다.

let formData = new FormData(document.querySelector('#form'));

axios.post("/api/xxx", formData).then(console.log).catch(console.error)

그리고 이것은 작동하지 않을 것입니다

let formData = new FormData(document.querySelector('#form'));

axios.post("/api/xxx", {data: formData}).then(console.log).catch(console.error)

postdata 매개변수 형식은 (url, {data: FormData}) 가 아니라 $ (url , FormData) 여야 합니다.

beforeAll(function (done) {

          //parse form fields
          var parsefields = function(req,res){
            var form = new formidable.IncomingForm();
            form.parse(req, function (err, fields, files) {
              if (err) res.status(404).json(err)
              else res.status(200).json(fields);
            });  
          }

          router.route('parsefields').post(parsefields)

          //start server
          s = express()
          s.use('/',router)
          s.listen(4000,(err)=>{done(err)})
          done()
        });

        it('should parse and return form fields', function (done) {

          const fd = new FormData()
          fd.append('key','value')

          axios({
            method: 'POST',
            url: 'http://localhost:4000/parsefields',
            data: fd,
            headers : fd.getHeaders(),
          }).then(function (res) {
            expect(res).to.exist
            expect(res.body.key).to.equals('value')
          }).catch(err => {
            expect(err).not.to.exist
          })
          done()

        });
});

같은 문제가 있습니다. 오류 없이 404를 수신합니다. Form parser, express 및 axios에 강력한 사용.

이것이 누군가에게 도움이 되는지 모르겠지만 Safari에서만 이 문제를 보고 formdata-polyfill 을 사용하여 수정했습니다. Safari는 기본적으로 FormData.append()를 지원해야 하지만 구현이 약간 다를 수 있습니까?

편집: 잘못했습니다: Blob에서 만든 URL을 사용하고 있었습니다. 올바른 얼룩을 사용하기 시작하면 모두 매력처럼 작동했습니다!

파일을 업로드할 수 있는 동안 Blob에 동일한 문제가 있습니다. Blob에서 파일로 변환하는 것은 간단하지만 이것이 버그인지 아니면 구문을 잘못 해석했는지 알고 싶습니다.

`` js upload () { let data = new FormData() data.append('file', this.croppedFile) data.append('blob', this.croppedBlob, 'blob.jpeg') axios.post('/api/fp/process/', data, { headers: { 'Accept': 텍스트/일반`,
},
})

croppedFile is derived from croppedBlob with this simple code:
   `   return new File([this.cropImg], this.file.name, { type: this.file.type })`

Firefox dev tools show:

------WebKitFormBoundarytmInU7WtcHvmgYbc
내용 처리: 양식 데이터; 이름 = "블롭"

------WebKitFormBoundarytmInU7WtcHvmgYbc
내용 처리: 양식 데이터; 이름 = "파일"; 파일명="dscn2950.jpg"
콘텐츠 유형: 이미지/jpeg

블롭:http :// localhost:8080/9a6446d1-1ca2-4fd3-a6c8-8b36d863c146
------WebKitFormBoundarytmInU7WtcHvmgYbc--

```
mozilla formData.append 문서 에 따르면 Blob 개체를 사용할 수 있는 것 같습니다.

나를 막힌 것은 내 서버가 https://www.npmjs.com/package/multer 를 사용하여 파일을 제대로 처리하지 못했다는 것입니다.

그것은 나를 위해 유용합니다! 감사 해요!

내 코드가 완벽하게 좋았기 때문에 여기에서는 아무 것도 효과가 없었습니다.
실제 문제는 Windows 검색 결과에서 끌어온 파일에 있었습니다. Chrome은 실제 위치를 찾지 못해 전체 FormData 구문 분석을 중단했습니다. 파일을 탐색하고 끌어서 문제를 해결했습니다.

안녕하세요 여러분,
도와주세요.

POST https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart HTTP/1.1
승인: 전달자 [YOUR_AUTH_TOKEN]
콘텐츠 유형: 멀티파트/관련; 경계=foo_bar_baz
콘텐츠 길이: [NUMBER_OF_BYTES_IN_ENTIRE_REQUEST_BODY]

--foo_bar_baz
콘텐츠 유형: application/json; 문자 집합=UTF-8

{
"이름": "myObject"
}

--foo_bar_baz
콘텐츠 유형: 이미지/jpeg

[JPEG_DATA]
--foo_bar_baz--

axios는 멀티파트/관련 요청 유형을 지원하지 않습니다.

저에게는 (아마도) 꿀꺽 꿀꺽 꿀꺽 마셨습니다. 내 서버의 축소된 파일에 오류가 발생했기 때문입니다. dist 폴더에서 모든 것을 수동으로 삭제하고 콘텐츠 유형을 정의되지 않은 상태로 두었고 Everythingg는 예상대로 작동합니다.
따라서 다음과 같은 sth를 갖게 됩니다.

formdata.append("selectPaymentType", $scope.extraFields.selectPaymentType);
formdata.append("pickupMethod", $scope.extraFields.selectPickupType);
요청하자 = {
메소드: 'POST',
url: baseURL + '주문',
데이터: formdata,
헤더: {
'콘텐츠 유형': 정의되지 않음,
'x-액세스 토큰': $scope.userToken
}
};
$http(요청)
.success(함수(d) { })
.오류(함수() { });

추신: 이것은 발췌한 것입니다 ... 또한 파일과 더 많은 필드를 첨부합니다...

섬기는 사람:

var 형식 = 새로운 multiparty.Form({uploadDir : './uploads/orders/'});

form.parse(req, function(err, 필드, 파일) {
//여기에 귀하의 코드
})

안녕하세요 plz 도움이 필요합니다: "파일: 이 값은 공백이 아니어야 합니다." fetch를 사용하여 게시물 이미지를 가져오려고 할 때 :
handleSubmit = (event) => { event.preventDefault(); //const { category } = this.state; console.log(this.state.file) let formData = new FormData(); formData.append("file",this.state.file); formData.append("name",this.state.name); alert('You Added a new Category Named ' + this.state.file); fetch(`${process.env.REACT_APP_BASE_URL}/category/image`, { method: 'POST', body: formData }).then(res => res.json()).then(err => console.log(err)); } 생성자(소품) {
슈퍼(소품);

this.state = {

    name: '',
    file: null
  ,
  isLoaded: false,
  isEditMode: false,

}

}
```

누구에게나 이것은 나를 위해 일했습니다.
입력 파일을 사용하는 경우 다른 입력 필드를 가져오기 전에 미들웨어처럼 router.post('/')에서 MULTER를 사용해야 합니다.

axios.create를 확인하십시오. 이 헤더는 "headers:{}"여야 하며 다음과 같이 data.like를 사용해서는 안 됩니다.
var 인스턴스 = axios.create({
헤더: {
// '콘텐츠 유형': 'application/x-www-form-urlencoded;charset=UTF-8',
},
// 데이터: {},
매개변수: {}
});

현재까지 이것은 nodejs에서 작동하지 않습니다. request-promise 접근 방식도 저에게 효과적이었습니다.

nodejs에서 axios와 함께 작동하도록 하기 위해 2일을 보냈습니다. 실제로 nodejs에서 request-promise와 함께 작동하도록 30초를 보냈습니다.

다른 솔루션을 시도했지만 결국 헤더를 추가하여이 문제를 처리했습니다.

const FormData = require('form-data')
const axios = require('axios')

const form = new FormData()
form.append('foo', 'bar')

await axios.post('http://myserver', form, { headers: form.getHeaders() })

@구그로쉬 네. 예. 예.

클라이언트 또는 서버 구성과 관련이 있는지 파악하는 데 반나절을 보냈습니다.
결국 headers: form.getHeaders() 이 트릭을 수행했습니다.

formDatamultipart/form-data 로 _작동_하기 때문에 got 로 이동했습니다. - https://github.com/sindresorhus/got 🙌
가깝지만 시가는 없습니다 Axios 👋

  const form = new FormData()
  const stream = fs.createReadStream(file.path)

  form.append('file', stream, file.name)

  try {
    await got.post('http://example.com', { body: form })
  } catch (error) {
    next(error)
  }

다음과 같은 방법으로 할 수 있습니다.
handleSubmit = (e: any) => {
e.preventDefault();
const 데이터 = 새로운 FormData();
data.append('product_csv', this.state.csvfile);
let accessToken = localStorage.getItem('access_token');
액시오스
.post('/업로드', 데이터,
{ 헤더:
{ '콘텐츠 유형': 'multipart/form-data', 권한 부여: accessToken }
})
.then(res => {
console.log('res', res);
});
};

@Googrosh Brilliant, .getHeaders() 저에게도 효과가 있었습니다. 나는 이것을 위해 얼마나 많은 시간을 보냈는지 말할 수 없습니다. 감사 해요!

반응 네이티브를 사용하고 있습니다. 그리고 rn-fetch-blob 를 사용하여 이 문제를 해결했습니다. 너무 나쁘다 :(

동일한 문제가 있습니다. 파일이 없는 간단한 FormData에서는 작동하지 않으며 .getHeaders()는 도움이 되지 않습니다. 작동하는 "가져온" 라이브러리로 이동했습니다. 여기에서도 언급했습니다 https://github.com/form-data/form-data/issues/458 (저는 Node v12를 사용하고 있습니다)

2020 ES6 작업 방식

HTML 형식으로 다음과 같이 데이터에 바인딩했습니다.

데이터:

form: {
   name: 'Joan Cap de porc',
   email: '[email protected]',
   phone: 2323,
   query: 'cap d\ou'
   file: null,
   legal: false
},

제출 시:

async submitForm() {
  const formData = new FormData()
  Object.keys(this.form).forEach((key) => {
    formData.append(key, this.form[key])
  })

  try {
    await this.$axios.post('/ajax/contact/contact-us', formData)
    this.$emit('formSent')
  } catch (err) {
    this.errors.push('form_error')
  }
}

참조: https://github.com/axios/axios/issues/789#issuecomment -508114703

받는 쪽에서 Express를 사용하는 경우 multer 가 필요 합니다. body-parser는 멀티파트 요청 구문 분석을 처리하지 않습니다.

@DespertaWeb 파일이 없을 때는 동작하지 않습니다.

이 페이지가 도움이 되었나요?
0 / 5 - 0 등급