Aws Api Gateway Upload File 415 Unsupported Media Type
aws api gateway upload file 415 Unsupported Media Type
一般情况下,前端向服务端上传文件的方式基本如下:
const formData = new FormData();
formData.append("userInfo", "{'name':'hello'}");
formData.append("file", file,'filename');
const request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
一般的后端,按照上方的代码就能够接收并处理。但是如果你遇到的是aws api gateway,那么很大概率会遭遇415 Unsupported Media Type
。原因是aws api gateway在有文件和字符串混合的情况下,是无法分辨的,他会以为你发送的是oct-stream。所以为了避免这种情况的发生,你需要换一种方式来改写代码:
const formData = new FormData();
const blob = new Blob(["{'name':'hello'}"], {type : 'application/json'});
formData.append("userInfo", blob);
formData.append("file", file,'filename');
const request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
这样改写一下,就能够避免发生415 Unsupported Media Type
的发生。