Aws pre-signed URLs 上传文件,带进度显示

  • 作者: 凯哥Java(公众号:凯哥Java)
  • 工作小总结
  • 时间:2022-02-19 00:46
  • 2480人已阅读
简介 在使用AWS上传文件的时候,有时候需要回显进度条及网速。这里使用的是与提交的url上传。与提交的url是后端返回的。

🔔🔔好消息!好消息!🔔🔔

 如果您需要注册ChatGPT,想要升级ChatGPT4。凯哥可以代注册ChatGPT账号代升级ChatGPT4

有需要的朋友👉:微信号 kaigejava2022


<input type="file" id="selector" multiple>
<button onclick="upload()">Upload</button>

<div id="status">No uploads</div>

<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">

 function upload() {
   [$('#selector')[0].files].forEach(fileObj => {
     var file = fileObj[0]
     // 从服务器获取一个URL
     retrieveNewURL(file, url => {
       // 上传文件到服务器
       uploadFile(file, url)
     })
   })
 }

 // 发请求到Node.js server获取上传URL。
 function retrieveNewURL(file, cb) {
   $.get(`YourUrl?name=${file.name}`, (url) => {
     cb(url)
   })
 }

 // 使用XMLHttpRequest来上传文件到S3。
 function uploadFile(file, url) {
     var xhr = new XMLHttpRequest ()

     // 加载进度条
     xhr.upload.onprogress = function (e) {
         // For uploads
         if (e.lengthComputable) {
             console.log(e.loaded / e.total);
             $('#status').text('上传进度:' + ((e.loaded / e.total)*100).toFixed(2) + '%');
         }
     };
     xhr.open('PUT', url, true)
     xhr.send(file)


     xhr.onload = () => {
       if (xhr.status == 200) {
         $('#status').text(`${file.name} 上传成功。`)
       }
     }
 }

</script>



https://www.cnblogs.com/codeaaa/p/10594233.html

TopTop