当前位置: 首页 > 面试题库 >

如何使用JS提取API上传文件?

申屠亦
2023-03-14
问题内容

我仍在努力寻找解决方案。

我可以让用户使用文件输入来选择文件(甚至多个):

<form>
  <div>
    <label>Select file to upload</label>
    <input type="file">
  </div>
  <button type="submit">Convert</button>
</form>

我可以submit使用捕获事件<fill in your event handler here>。但是一旦完成,如何使用发送文件fetch

fetch('/files', {
  method: 'post',
  // what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);

问题答案:

这是带有注释的基本示例。该upload功能是您要寻找的:

// Select your input type file and store it in a variable
const input = document.getElementById('fileinput');

// This will upload the file after having read it
const upload = (file) => {
  fetch('http://www.example.net', { // Your POST endpoint
    method: 'POST',
    headers: {
      // Content-Type may need to be completely **omitted**
      // or you may need something
      "Content-Type": "You will perhaps need to define a content-type here"
    },
    body: file // This is your file object
  }).then(
    response => response.json() // if the response is a JSON object
  ).then(
    success => console.log(success) // Handle the success response object
  ).catch(
    error => console.log(error) // Handle the error response object
  );
};

// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files[0]);

// Add a listener on your input
// It will be triggered when a file will be selected
input.addEventListener('change', onSelectFile, false);


 类似资料:
  • 我仍在努力想办法解决这个问题。 我可以让用户使用文件输入选择文件(甚至多个): 我可以使用

  • 有没有人可以帮助我如何在django rest api中使用POST方法上传文件,例如当我启动时 我是Django REST API的新手,我阅读了文档http://www.django-rest-framework.org/api-guide/parsers.html#FileuploadParser,但仍然不知道如何实现它

  • 出身背景 我目前有一个正在工作的C#代码,可以从网页上读取HTTP POST表单提交中的值。看起来是这样的: 我也有工作代码从页面上的文件上传控件读取附件: 显然,最后一段代码还有一点,但我希望它至少能说明我的问题。 我的问题 我现在尝试将这两段代码结合起来。我认为将数据传输对象放在Post函数中一样简单: 这导致在执行HTTP POST时,以下内容返回到浏览器: {“Message”:“此资源不

  • 基本上,我正在尝试使用Web API 2上传图像和枚举。 这是控制器签名: 问题是,每当我尝试发布一个多部分表单(包含一个文件和一个类型)时,我都会收到一个415错误: {“Message”:“此资源不支持请求实体的媒体类型‘multipart/form data’。”,“ExceptionMessage”:“没有MediaTypeFormatter可用于从媒体类型为“multipart/form

  • 在Android上,我正在尝试使用Google Drive API:Insert File上传Cordova / Phonegap getPicture()的输出。有没有办法使用FILE_URI而不是DATA_URL(base64)来执行此操作? 我试过相机。目的地类型。首先是DATA_URL,但它没有像应该的那样返回Base64数据,它只返回了与FILE_URI相同的内容。因此,现在我正试图弄清

  • 我正在尝试使用angularjs和spring MVC上传一个文件 在application-context.xml中有一个multipartResolver bean。 我表单如下所示: