sourcecode

양식 데이터 다중 부분/양식 데이터에서 경계를 가져오거나 설정하는 방법 - 각도

codebag 2023. 10. 5. 21:33
반응형

양식 데이터 다중 부분/양식 데이터에서 경계를 가져오거나 설정하는 방법 - 각도

브라우저에서 엔드포인트에 양식 데이터를 게시해야 하는 미니 앱이 있습니다.

제 글입니다.

var formData = new FormData();
formData.append('blobImage', blob, 'imagem' + (new Date()).getTime());

return $http({
  method: 'POST',
  url: api + '/url',
  data: formData,
  headers: {'Content-Type': 'multipart/form-data'}
})

파라미터에 formData로 경계가 추가되는 것 같은데 헤더로 보낼 수가 없는데 어떻게 해야 하나요?

머리글 내용을 보니올바른 경계를 추가하려면 유형을 정의하지 않아야 합니다.

올바른 방법은 설정하지 않는 것이었습니다.Content-Type머리말

var formData = new FormData();
formData.append('blobImage', blob, 'imagem' + (new Date()).getTime());

return $http({
  method: 'POST',
  url: api + '/url',
  data: formData,
  // headers: {'Content-Type': 'multipart/form-data'}
})

기타 머리글(예:Authorization괜찮습니다).다음은 예입니다.

import { http } from '@angular/common/http'

function sendPostData(form: FormData) {
  const url = `https://post-url-example.com/submit`;
  const options = {
    headers: new HttpHeaders({
      Authorization: `Bearer auth-token`
    })
  };

  return http.post(url, form, options);
}

파블로의 답을 추가합니다

http request body가 a를 가질 때FormData유형, 각도 의지 연기Content-Type브라우저에 헤더를 할당합니다.detectContentTypeHeader()돌아올 것입니다null위에FormDatarequest body와 angular는 request header를 설정하지 않습니다.

이거 나왔어요.@angular/commons/http/src/xhr.ts모듈.

  // Auto-detect the Content-Type header if one isn't present already.
  if (!req.headers.has('Content-Type')) {
    const detectedType = req.detectContentTypeHeader();
    // Sometimes Content-Type detection fails.
    if (detectedType !== null) {
      xhr.setRequestHeader('Content-Type', detectedType);
    }
  }

요청 본문 기반의 Content-Type 탐지:

  detectContentTypeHeader(): string|null {
    // An empty body has no content type.
    if (this.body === null) {
      return null;
    }
    // FormData bodies rely on the browser's content type assignment.
    if (isFormData(this.body)) {
      return null;
    }
    // Blobs usually have their own content type. If it doesn't, then
    // no type can be inferred.
    if (isBlob(this.body)) {
      return this.body.type || null;
    }
    // Array buffers have unknown contents and thus no type can be inferred.
    if (isArrayBuffer(this.body)) {
      return null;
    }
    // Technically, strings could be a form of JSON data, but it's safe enough
    // to assume they're plain strings.
    if (typeof this.body === 'string') {
      return 'text/plain';
    }
    // `HttpUrlEncodedParams` has its own content-type.
    if (this.body instanceof HttpParams) {
      return 'application/x-www-form-urlencoded;charset=UTF-8';
    }
    // Arrays, objects, and numbers will be encoded as JSON.
    if (typeof this.body === 'object' || typeof this.body === 'number' ||
        Array.isArray(this.body)) {
      return 'application/json';
    }
    // No type could be inferred.
    return null;
  }

출처:

다른 사람이 이 일로 힘들어한다면...양식 날짜를 제출하는 경우 브라우저에서 내용 유형을 설정해야 합니다.이 작업을 수행하려면 멀티파트/폼-데이터에 대해 entrytype 헤더를 로 설정합니다.

const formData = new FormData();
formData.append('file', file);
let headers = new HttpHeaders();
headers = headers.append('enctype', 'multipart/form-data');
return this.http.post(path, formData, { headers: headers })

내용 유형을 설정하는 HttpInterceptor도 있으므로 entyp가 설정되지 않은 경우에만 설정합니다.

if (!req.headers.has('enctype')) {
headersConfig['Content-Type'] = 'application/json';
}

이게 도움이 됐으면 좋겠습니다.

언급URL : https://stackoverflow.com/questions/40351429/formdata-how-to-get-or-set-boundary-in-multipart-form-data-angular

반응형