Skip to content

Instantly share code, notes, and snippets.

@BranLiang
Last active March 6, 2019 12:59
Show Gist options
  • Save BranLiang/5fa65faf0e1dc97893583529bc9c9df3 to your computer and use it in GitHub Desktop.
Save BranLiang/5fa65faf0e1dc97893583529bc9c9df3 to your computer and use it in GitHub Desktop.
[File Uploaders] qiniu, qcloud #upload
import qiniu, { rs } from "qiniu";
import { File, ResourceTypes } from "@utils/interfaces";
import sanitize from 'sanitize-filename';
import uuidv4 from 'uuid/v4';
const mac = new qiniu.auth.digest.Mac(
process.env.QINIU_ACCESS_KEY,
process.env.QINIU_SECRET_KEY
);
const bucket = process.env.QINIU_BUCKET || 'yunshe-test'
const options: rs.PutPolicyOptions = {
scope: bucket,
returnBody: '{"key":"$(key)","bucket":"$(bucket)"}',
}
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken=putPolicy.uploadToken(mac);
const formUploader = new qiniu.form_up.FormUploader(options);
const putExtra = new qiniu.form_up.PutExtra();
export const uploadImage = async (
file: File,
entity: ResourceTypes,
id: string
) => {
const { filename, stream } = await file;
const sanitized = sanitize(filename);
const encoded = encodeURIComponent(sanitized);
const key = `${entity}/${id}/${uuidv4()}-${encoded}`;
return new Promise((resolve, reject) => {
formUploader.putStream(uploadToken, key, stream, putExtra, (respErr, respBody, respInfo) => {
if (respErr) {
throw respErr;
}
if (respInfo.statusCode == 200) {
resolve(respBody);
} else {
reject(respBody);
}
})
})
}
import { IFile, ResourceTypes } from "@utils/interfaces";
import COS from "cos-nodejs-sdk-v5";
import sanitize from "sanitize-filename";
import uuidv4 from "uuid/v4";
const cos = new COS({
SecretId: process.env.COS_SECRET_ID,
SecretKey: process.env.COS_SECRET_KEY,
});
const bucket = process.env.COS_BUCKET;
const region = process.env.COS_REGION || "ap-shanghai";
export const uploadImage = async (
file: IFile,
entity: ResourceTypes,
id: string,
) => {
const { filename, stream } = await file;
const sanitized = sanitize(filename);
const encoded = encodeURIComponent(sanitized);
const key = `${entity.toLocaleLowerCase()}/${id}/${uuidv4()}-${encoded}`;
return new Promise((resolve) => {
cos.putObject({
Bucket: bucket,
Region: region,
Key: key,
Body: stream,
}, (err, data) => {
if (err) {
throw err;
} else {
resolve(data);
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment