高级前端
js
【Q463】前端如何实现文件上传功能

前端如何实现文件上传功能

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 471 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

Blob ->

Author 回答者: hsq777 (opens in a new tab)

将input的类型设置为file,再加一个按钮就行

<input type="file" ref="referenceUpload" @change="onUpload"></input>
<button type="primary" style="margin: 0px 0px 0px -83px;">上传文件</button>

Author 回答者: HydratedPig (opens in a new tab)

html 中直接设置 input 的类型为 file 就可以实现上传了

// HTML <input type="file" id="upload" />
// JS
const uploadInput = document.getElementById("upload");
const handleUpload = (event) => {
  const file = event.target.files[0];
  const formData = new FormData();
  formData.append("file", file);
  // 文件上传操作
};
uploadInput.addEventListener("change", handleUpload);

Author 回答者: HydratedPig (opens in a new tab)

html 中直接设置 input 的类型为 file 就可以实现上传了

// HTML
<input type="file" id="upload"/>
// JS
const uploadInput = document.getElementById("upload");
const handleUpload = (event) => {
  const file = event.target.files[0];
  const formData = new FormData();
  formData.append("file", file);
  // 文件上传操作
};
uploadInput.addEventListener("change", handleUpload);

当然也可以放在表单里,统一提交表单 MDN (opens in a new tab)的示例里还告诉我们input 各个浏览器长得不一样,我们也可以用其他东西隐藏 input