极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

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

Issue

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

Blob ->

Author

回答者: hsq777 (opens new window)

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

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

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);

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 new window)的示例里还告诉我们 input 各个浏览器长得不一样,我们也可以用其他东西隐藏 input

Last Updated: 2/13/2023, 10:50:25 AM