uploadFile.vue 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <template>
  2. <div class="uploadBox"></div>
  3. </template>
  4. <script>
  5. import "../../../../../../common/aws-sdk-2.235.1.min.js";
  6. export default {
  7. props:{
  8. index:{
  9. type:String,
  10. default:"0"
  11. },
  12. },
  13. data() {
  14. return {
  15. bucket: "", //aws上传接口
  16. bucketname: "ccrb", //桶
  17. uploadid: "",
  18. partsize: 10 * 1024 * 1024, //10MB 分片
  19. filestate: {
  20. status: "", //有 error(直接报错) 和 fail(上传的时候报错) 和 success(上传成功) 和 processing(上传中)
  21. percent: "", //(0-100的进度)
  22. },
  23. file: null,
  24. flag:true,
  25. };
  26. },
  27. watch: {
  28. filestate: {
  29. handler(newValue) {
  30. this.$emit("progressUpdate", {index:this.index,...newValue});
  31. },
  32. immediate: true,
  33. deep: true,
  34. },
  35. },
  36. methods: {
  37. //--------------------------分断上传保证稳定性
  38. //初始化上传
  39. // async init(){
  40. // const credentials = {
  41. // accessKeyId: "AKIATLPEDU37QV5CHLMH",
  42. // secretAccessKey: "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",
  43. // }; //秘钥形式的登录上传
  44. // window.AWS.config.update(credentials);
  45. // window.AWS.config.region = "cn-northwest-1"; //设置区域
  46. // //桶的设置
  47. // bucket = new window.AWS.S3({
  48. // params: {
  49. // Bucket: this.bucketname
  50. // }
  51. // });
  52. // return bucket;
  53. // },
  54. // 初始化上传入口
  55. async initMultipartUpload(key, file) {
  56. const params = {
  57. Bucket: this.bucketname,
  58. Key: key,
  59. ContentType: file.type,
  60. ACL: "public-read",
  61. };
  62. //创建一个续传通道
  63. const data = await this.bucket.createMultipartUpload(params).promise();
  64. return data.UploadId;
  65. },
  66. // 上传文件的某一部分
  67. async uploadPart(file, keyname, uploadid, pn, start, end) {
  68. //key可以设置为桶的相对路径,Body为文件, ACL最好要设置
  69. if(!this.flag)return;
  70. var params = {
  71. Bucket: this.bucketname,
  72. Key: keyname,
  73. // ContentType: file.type,
  74. PartNumber: pn,
  75. UploadId: uploadid,
  76. Body: file.slice(start, end),
  77. // "Access-Control-Allow-Credentials": "*",
  78. // ACL: "public-read",
  79. };
  80. const result = await this.bucket.uploadPart(params).promise();
  81. return { ETag: result.ETag, PartNumber: pn };
  82. },
  83. //完成分块上传
  84. async completeMultipartUpload(parts, keyname, uploadid) {
  85. if(!this.flag)return;
  86. const params = {
  87. Bucket: this.bucketname,
  88. Key: keyname,
  89. MultipartUpload: { Parts: parts },
  90. UploadId: uploadid,
  91. };
  92. return await this.bucket.completeMultipartUpload(params).promise();
  93. },
  94. async abortMultipartUpload(key, uploadid) {
  95. const params = {
  96. Bucket: this.bucketname,
  97. Key: key,
  98. UploadId: uploadid,
  99. };
  100. let data = await this.bucket.abortMultipartUpload(params).promise();
  101. this.$emit("delUpload",{index:this.index})
  102. },
  103. //--------------------------------下面支持断点续传
  104. //初始化亚马逊参数
  105. async init() {
  106. //秘钥形式的登录上传
  107. const credentials = {
  108. accessKeyId: "AKIATLPEDU37QV5CHLMH",
  109. secretAccessKey: "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",
  110. region: "cn-northwest-1",
  111. };
  112. window.AWS.config.update(credentials);
  113. // window.AWS.config.region = "cn-northwest-1"; //设置区域
  114. //桶的设置
  115. this.bucket = new window.AWS.S3({
  116. params: {
  117. Bucket: this.bucketname,
  118. },
  119. });
  120. return this.bucket;
  121. },
  122. //获取当前文件是否有已上传断点信息
  123. async getawscheckpoint(key) {
  124. let partsinfo;
  125. try {
  126. const result = await this.bucket
  127. .listMultipartUploads({ Bucket: this.bucketname, Prefix: key })
  128. .promise();
  129. //获取具体分片信息
  130. if (result.Uploads.length) {
  131. this.uploadid = result.Uploads[result.Uploads.length - 1].UploadId;
  132. partsinfo = await this.bucket
  133. .listParts({
  134. Bucket: this.bucketname,
  135. Key: key,
  136. UploadId: this.uploadid,
  137. })
  138. .promise();
  139. }
  140. } catch (err) {
  141. console.log(err);
  142. }
  143. return { uploadid: this.uploadid, partsinfo };
  144. },
  145. //分段上传
  146. async awsuploadpart(filestate, file, uploadid, parts, key) {
  147. var partarr = []; //已完成的数组
  148. //已完成的分片,转化成提交格式
  149. const completeparts = parts.map((_) => {
  150. partarr.push(_.PartNumber);
  151. return { PartNumber: _.PartNumber, ETag: _.ETag };
  152. });
  153. // 分块上传文件
  154. // parts = [];
  155. let uploadpart;
  156. let start = 0;
  157. let end = 0;
  158. let len = Math.ceil(file.size / this.partsize); //循环的长度
  159. if (partarr.length) {
  160. this.filestate.status = "processing";
  161. this.filestate.percent = parseInt((completeparts.length * 100) / len);
  162. }
  163. //循环上传
  164. for (let i = 0; i < len; i++) {
  165. if(!this.flag)break;
  166. start = i * this.partsize;
  167. end = (i + 1) * this.partsize;
  168. if (!partarr.includes(i+1)) {
  169. uploadpart = await this.uploadPart(
  170. file,
  171. key,
  172. uploadid,
  173. i + 1,
  174. start,
  175. end
  176. );
  177. if (uploadpart.ETag != null) {
  178. completeparts.push(uploadpart);
  179. partarr.push(uploadpart.PartNumber);
  180. this.filestate.status = "processing";
  181. this.filestate.percent = parseInt(
  182. (completeparts.length * 100) / len
  183. );
  184. } else {
  185. this.filestate.status = "fail";
  186. this.stopUpload();
  187. return;
  188. }
  189. }
  190. }
  191. //提交上传成功信息
  192. if(this.flag){
  193. let data = await this.completeMultipartUpload(
  194. completeparts,
  195. key,
  196. uploadid
  197. );
  198. this.filestate.status = "success";
  199. return data;
  200. }
  201. },
  202. //上传的接口
  203. async awsupload({ file = this.file, keyName, folderName }) {
  204. if (!file) return this.$message.error("请上传文件");
  205. this.init(); //初始化桶
  206. // const key = (folderid || uuidv4()) + "/" + file.name; //需要上传的文件名
  207. let key = "";
  208. if (keyName) {
  209. key = keyName;
  210. } else {
  211. if (folderName) {
  212. key = `${folderName}/${file.name}`;
  213. } else {
  214. key = `default/${file.name.split(".")[0] +
  215. new Date().getTime() +
  216. "." +
  217. file.name.split(".")[file.name.split(".").length - 1]}`;
  218. }
  219. }
  220. this.filestate = {
  221. percent: 0,
  222. status: "start",
  223. };
  224. this.filestate.percent = 0;
  225. this.filestate.status = "start";
  226. this.file = file;
  227. //上传的参数
  228. var params = {
  229. Bucket: this.bucketname,
  230. Key: key,
  231. };
  232. this.flag = true;
  233. //设置桶上传文件
  234. try {
  235. //检查文件是否已上传
  236. this.bucket.headObject(params, async (err, data) => {
  237. // 没有上传成功,head方法会返回失败
  238. if (err) {
  239. //检查是否部分上传
  240. const { uploadid, partsinfo } = await this.getawscheckpoint(
  241. key,
  242. this.bucket
  243. );
  244. //如果已经部分存在,那么直接在节点续传
  245. if (uploadid) {
  246. //断点续传
  247. this.$emit("startUpload", { index:this.index,key, uploadid });
  248. this.filestate.key = key;
  249. this.filestate.uploadid = uploadid;
  250. this.flag = true;
  251. let data = await this.awsuploadpart(
  252. this.filestate,
  253. file,
  254. uploadid,
  255. partsinfo.Parts,
  256. key
  257. );
  258. if(this.flag || this.filestate.percent==100)return this.$emit("success", {index:this.index, data, key, uploadid });
  259. // return {data,key,uploadid}
  260. }
  261. //不存在,上传新的
  262. else {
  263. const uploadid = await this.initMultipartUpload(key, file); //初始化文件上传
  264. this.$emit("startUpload", { index:this.index,key, uploadid });
  265. this.filestate.key = key;
  266. this.filestate.uploadid = uploadid;
  267. this.flag = true;
  268. let data = await this.awsuploadpart(
  269. this.filestate,
  270. file,
  271. uploadid,
  272. [],
  273. key
  274. );
  275. if(this.flag || this.filestate.percent==100)return this.$emit("success", {index:this.index, data, key, uploadid });
  276. // return {data,key,uploadid}
  277. }
  278. }
  279. //如果已经上传成功了,那么直接返回状态百分百
  280. else if (data) {
  281. //data存在,上传成功
  282. this.filestate.percent = 100;
  283. this.filestate.status = "success";
  284. let url = `https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/${key}`
  285. this.file = null;
  286. if(this.flag)return this.$emit("success", { index:this.index,data:{
  287. Key:key,
  288. Location:url,
  289. ETag:data.ETag,
  290. size:data.ContentLength,
  291. ServerSideEncryption:data.ServerSideEncryption,
  292. Bucket:this.bucketname
  293. } });
  294. // return {data,key,uploadid}
  295. }
  296. });
  297. } catch (err) {
  298. this.filestate.status = "error";
  299. this.stopUpload();
  300. console.log(err);
  301. }
  302. },
  303. // 停止上传
  304. stopUpload(){
  305. this.filestate.status = "stop";
  306. this.flag = false;
  307. }
  308. },
  309. mounted() {
  310. this.bucket = "";
  311. this.file = null;
  312. },
  313. };
  314. </script>
  315. <style scoped>
  316. .uploadBox {
  317. display: none;
  318. }
  319. </style>