阿里云OSS指定下载时文件名称

1,182 阅读1分钟

1. 参考官方文档设置不成功

阿里云OSS文档官网地址

image.png

2. 找到解决办法

'Content-Disposition': 'attachment; filename=' + encodeURIComponent(file.name),

image.png

3. Content-Disposition

Content-Disposition 详解

4. 点击上传的pdf文件是预览而不是下载

解决:

image.png

'Content-Type': 'application/octet-stream',

此外,文件后缀是大写(.PDF)才可以下载,小写后缀依然是预览

5. 完整代码aliyun.oss.client.js

const loginUserInfo = JSON.parse(localStorage.getItem('user')) || {};
const { accessKeyId, accessKeySecret, bucketName, prefix } = loginUserInfo.ossConfig || {};
/**
 * 阿里云oss上传工具
 */
const OSS = require('ali-oss');
const config = {
  region: 'oss-cn-hangzhou',
  accessKeyId,
  accessKeySecret,
  bucket: bucketName,
  secure: true,
};

/**
 * 配置
 */
const init = () => {
  return new OSS(config);
};

/**
 * 生成uuid
 */
const guid = () => {
  const S4 = () => {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  };
  return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
};

/**
 * 修改文件名字
 */
const fileName = (file) => {
  var uuid = prefix + '/oss' + guid();
  if (file.name) {
    const arr = file.name.split('.');
    if (arr.length > 1) {
      return uuid + '.' + arr[arr.length - 1];
    } else {
      return uuid;
    }
  } else {
    return `${uuid}.png`;
  }
};

const ossPut = (file) => {
  return new Promise((resolve, reject) => {
    const objectName = fileName(file);
    init()
      .put(objectName, file, {
        headers: {
          'Content-Disposition': 'attachment; filename=' + encodeURIComponent(file.name),
          'Content-Encoding': 'UTF-8',
          'Content-Type': 'application/octet-stream',
        },
      })
      .then(({ res, url }) => {
        if (res && res.status === 200) {
          // console.log('阿里云OSS上传文件成功回调', res, url);
          resolve(res, url);
        }
      })
      .catch((err) => {
        console.log('阿里云OSS上传文件失败回调', err);
        reject(err);
      });
  });
};

/**
 * 下载文件
 */
const ossGet = (name) => {
  return new Promise((resolve, reject) => {
    init()
      .get(name)
      .then(({ res }) => {
        if (res && res.status === 200) {
          // console.log('阿里云OSS下载文件成功回调', res);
          resolve(res);
        }
      })
      .catch((err) => {
        console.log('阿里云OSS下载文件失败回调', err);
        reject(err);
      });
  });
};

export { ossPut, ossGet };