#Vue3篇:预览文件获取input的file对象以及url转file对象

<template>
  <div>
    <input type="file" @change="handleFileChange" ref="fileInput" accept="*/*" />
    <br />
    <br />
    <!-- 上传按钮 -->
    <button @click="onUploadFile" :disabled="!selectedFile">
      上传文件
    </button>
    <br />
    <br />
    <button @click="onPreviewFile">预览test</button>
    <br>
    <br>
    <button @click="onUrlToBlob">线上url转file</button>
    <br>
    <br>
    <button @click="onChooseFile">钉钉chooseFile</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import router from '@/router';
import { upLoadFile,upLoadFileTest, urlToFile,commonUploadFile } from './file'
import dingtalkUtils from '@/utils/dingtalkUtils'

const fileInput = ref(null);
const selectedFile = ref(null);

// 处理文件选择
const handleFileChange = (event) => {
  const files = event.target.files;
  console.log('@@@input选择的文件: ', files);
  console.log(files)
  console.log('files: ', files);
  if (files && files.length > 0) {
    selectedFile.value = files[0];
  }
};

// input选择文件
const onUploadFile =  () => {
  commonFile()
};
// 钉钉选择文件
const onChooseFile = async () => { 
  const res  = await dingtalkUtils.getChooseFile()
  selectedFile.value = res
  console.log('  selectedFile.value : ',   selectedFile.value );
  commonFile()
  console.log('@@@res: ', res);
};
// 上传文件到服务器
const commonFile =  () => {
  if (!selectedFile.value) return;
  // commonUploadFile(selectedFile.value)
  const formData = new FormData();
  // formData.append('file', files.value);
  formData.append('file', selectedFile.value);
  formData.append('storageType', 'aliyun'); // 可选附加数据
  formData.append('accessType', 'public'); // 可选附加数据
  const params = {
    url: '/upload-test/api/comm/upload',
    formData: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
      'token': '9e65cb5f679449bab32d9593ddf44ddc',
      'userid': '1655738390099988482'
    },
  }
  upLoadFileTest(params).then(res => {
    console.log('@@@res服务器返回: ', res);
  });
}
// 预览
const onPreviewFile = () => {
  router.push({
    path: '/file-preview',
  });
}
// url

const onUrlToBlob = () => {
  // 使用示例
  // const fileUrl = 'https://e-inhouse-test.longi.com:50446/api/comm/download/aliyun/public/2025-05-23/1adfd72b478b4f188cde89234fd0f445.png';
  // 50MB
  const fileUrl = 'https://e-inhouse-test.longi.com:50446/api/comm/download/aliyun/public/2025-05-23/53bed974079243dcb8015457d65da1c7.png';
  const urlObj = new URL(fileUrl);
  const fileNameFromURL = urlObj.pathname.split('/').pop();
  const mimeTypes = {
    'png': 'image/png',
    'jpg': 'image/jpeg',
    'jpeg': 'image/jpeg',
    'pdf': 'application/pdf',
  };
// 获取文件扩展名(转换为小写)
const fileExtension = fileNameFromURL.split('.').pop().toLowerCase();
  urlToFile(fileUrl, fileNameFromURL, mimeTypes)
    .then(file => {
      console.log('File对象11:', file);
      selectedFile.value = file;
      commonFile()
      // 输出示例:File { name: "document.pdf", type: "application/pdf", ... }
    });

}

// 重置文件输入
const resetFileInput = () => {
  selectedFile.value = null;
  if (fileInput.value) {
    fileInput.value.value = ''; // 清除input的值
  }
};
</script>

<style scoped>
.progress {
  color: #42b983;
  font-weight: bold;
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>

// {
// "code": 200,
// "msg": "成功",
// "data": {
// "id": "1925740282018086913",
// "createBy": "1655738390099988482",
// "createTime": "2025-05-23 10:27:16",
// "updateBy": "1655738390099988482",
// "updateTime": "2025-05-23 10:27:16",
// "name": "image.png",
// "contentType": "application/octet-stream",
// "size": 223383,
// "storageType": "aliyun",
// "path": "public/2025-05-23/0bf67699b1214b34a2d3d9c06bb87fe8.png",
// "url":
"https://e-inhouse-test.longi.com:50446/api/comm/download/aliyun/public/2025-05-23/0bf67699b1214b34a2d3d9c06bb87fe8.png"
// }
// }

/*
*file.js
*/

// import axios from 'axios';
// import router from '@/router'
// import mainService from '@/services/main'
// const mimeTypes = {
//   // 图片类型
//   'png': 'image/png',
//   'jpg': 'image/jpeg',
//   'jpeg': 'image/jpeg',
//   'gif': 'image/gif',
//   'webp': 'image/webp',
//   'svg': 'image/svg+xml',
//   'bmp': 'image/bmp',
//   'ico': 'image/x-icon',
//   'tiff': 'image/tiff',

//   // 文档类型
//   'pdf': 'application/pdf',
//   'doc': 'application/msword',
//   'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
//   'xls': 'application/vnd.ms-excel',
//   'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
//   'ppt': 'application/vnd.ms-powerpoint',
//   'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
//   'txt': 'text/plain',
//   'csv': 'text/csv',
//   'rtf': 'application/rtf',
//   'odt': 'application/vnd.oasis.opendocument.text',
//   'ods': 'application/vnd.oasis.opendocument.spreadsheet',

//   // 压缩包类型
//   'zip': 'application/zip',
//   'rar': 'application/x-rar-compressed',
//   '7z': 'application/x-7z-compressed',
//   'tar': 'application/x-tar',
//   'gz': 'application/gzip',

//   // 音视频类型
//   'mp3': 'audio/mpeg',
//   'wav': 'audio/wav',
//   'ogg': 'audio/ogg',
//   'mp4': 'video/mp4',
//   'webm': 'video/webm',
//   'mov': 'video/quicktime',
//   'avi': 'video/x-msvideo',
//   'mkv': 'video/x-matroska',

//   // 编程相关
//   'js': 'application/javascript',
//   'json': 'application/json',
//   'html': 'text/html',
//   'css': 'text/css',
//   'xml': 'application/xml',
//   'php': 'application/x-httpd-php',
//   'py': 'text/x-python',
//   'java': 'text/x-java-source',
//   'c': 'text/x-c',
//   'cpp': 'text/x-c++src',
//   'h': 'text/x-chdr',
//   'sh': 'application/x-sh',
//   'bat': 'application/x-msdownload',

//   // 其他
//   'exe': 'application/x-msdownload',
//   'dll': 'application/x-msdownload',
//   'apk': 'application/vnd.android.package-archive',
//   'ipa': 'application/octet-stream',
//   'deb': 'application/x-debian-package',
//   'rpm': 'application/x-redhat-package-manager',
//   'iso': 'application/x-iso9660-image',
//   'dmg': 'application/x-apple-diskimage',
// };
// function getMimeType(filename) {
//   const extension = filename.split('.').pop().toLowerCase();
//   return mimeTypes[extension] || 'application/octet-stream'; // 默认类型
// }
// export const commonUploadFile =  (fileObj) => {
//   if (!fileObj) return;
//   const formData = new FormData();
//   formData.append('file', fileObj);
//   const config = {
//     data: formData,
//     headers: {
//       'Content-Type': 'multipart/form-data',
//     },
//   }
//   mainService.getFilePreviewUrl(config).then(res => {
//     console.log('res: ', res);
//     console.log('res.data: ', res.data);
//      router.push({
//           name: 'Preview',
//           params: {
//             linkUrl: res.link,
//           },
//         })
//   })
//   // const params = {
//   //   url: '/file/gw/ldp/ldp-tenant-osca/v1/public/upload/link',
//   //   formData: formData,
//   //   headers: {
//   //     'Content-Type': 'multipart/form-data',
//   //   },
//   // }
//   // upLoadFile(params)
// }  
// // export const commonUploadFile =  (fileObj) => {
// //   if (!fileObj) return;
// //   const formData = new FormData();
// //   formData.append('file', fileObj);
// //   const params = {
// //     url: '/file/gw/ldp/ldp-tenant-osca/v1/public/upload/link',
// //     formData: formData,
// //     headers: {
// //       'Content-Type': 'multipart/form-data',
// //     },
// //   }
// //   upLoadFile(params)
// // }  
// // export async function upLoadFile(config) {
// //   return new Promise((resolve, reject) => {
// //     const { url, formData, headers } = config
// //     axios
// //       .post(url, formData, {
// //         headers,
// //       })
// //       .then((res) => {
// //         const linkUrl = res?.data?.data?.data.link
// //         router.push({
// //           name: 'Preview',
// //           params: {
// //             linkUrl,
// //           },
// //         })
// //       })
// //   })
// // }

// export async function urlToFile(url) {
//   const response = await fetch(url);
//   const blob = await response.blob();
//   const fileName = url.split('/').pop();
//   const mimeType = getMimeType(fileName);
//   const file = new File([blob], fileName, { type: mimeType || blob.type });
//   console.log('@@@url转file对象: ', file);
//   commonUploadFile(file) // 上传文件
// }

// export async function upLoadFileTest(config) {
//   return new Promise((resolve, reject) => {
//     const { url, formData, headers } = config
//     axios
//       .post(url, formData, {
//         headers: headers,
//       })
//       .then((res) => {
//         if (res.status === 200 && res.data?.code === 200) {
//           console.log('res: ', res)
//           resolve(res.data.data)
//         } else {
//           reject(res.data)
//         }
//       })
//   })
// }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值