rogerxu / rogerxu.github.io

Roger Xu's Blog
3 stars 2 forks source link

File API #213

Open rogerxu opened 6 years ago

rogerxu commented 6 years ago

File - Web API 接口参考 | MDN

rogerxu commented 4 years ago

Blob

rogerxu commented 4 years ago

File

在web应用程序中使用文件 - Web API 接口参考 | MDN

rogerxu commented 4 years ago

Download

http - Do I need Content-Type: application/octet-stream for file download? - Stack Overflow

关于http:我是否需要Content-Type:application / octet-stream进行文件下载? | 码农家园

Content-Disposition - HTTP | MDN

function downloadFile() {
  window.location.href = '/download';
}

Request:

GET /download

Response:

200 OK
Content-Type: application/json
Content-Disposition: attachment; filename="cool.json"
Content-Length: 22

{"ok":true}
rogerxu commented 4 years ago

Upload

Form

Content-Type: multipart/form-data

<form name="form" action="/upload" method="POST" target="upload_iframe" enctype="multipart/form-data">
  <input name="name" type="text" value="some name">
  <textarea name="descr" cols="30" rows="10">some text</textarea>
  <input name="file" type="file" accept=".json">
</form>

<iframe name="upload_iframe"></iframe>
POST /upload
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryKNa6BjYK9NAgijek

------WebKitFormBoundaryKNa6BjYK9NAgijek
Content-Disposition: form-data; name="name"

some name
------WebKitFormBoundaryKNa6BjYK9NAgijek
Content-Disposition: form-data; name="descr"

some text
------WebKitFormBoundaryKNa6BjYK9NAgijek
Content-Disposition: form-data; name="file"; filename="file.json"
Content-Type: application/json

{
  "ok": true
}
------WebKitFormBoundaryKNa6BjYK9NAgijek--

XMLHttpRequest

FormData 对象的使用 - Web API 接口参考 | MDN

var formData = new FormData();

formData.append('name', 'some name');
formData.append('descr', 123456); // number will be converted to string
formData.append('file', fileInputElement.files[0]);

var xhr = new XMLHttpRequest();
xhr.setRequestHeader('X-CSRF-Token', 'csrf-token-dummy');
xhr.open('POST', '/upload');
xhr.send(formData);

通过jQuery Ajax使用FormData对象上传文件 - 简书

jQuery.ajax({
  url: '/upload',
  type: 'POST',
  headers: {
    'X-CSRF-Token': 'csrf-token-dummy',
  },
  data: formData,
  processData: false,
  contentType: false,
});

Request:

POST /upload
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryKNa6BjYK9NAgijek
X-CSRF-Token: csrf-token-dummy

------WebKitFormBoundaryKNa6BjYK9NAgijek
Content-Disposition: form-data; name="name"

some name
------WebKitFormBoundaryKNa6BjYK9NAgijek
Content-Disposition: form-data; name="descr"

some text
------WebKitFormBoundaryKNa6BjYK9NAgijek
Content-Disposition: form-data; name="file"; filename="file.json"
Content-Type: application/json

{
  "ok": true
}
------WebKitFormBoundaryKNa6BjYK9NAgijek--