feat:上传文件用月份路径

This commit is contained in:
李亮亮 2024-01-15 17:01:06 +08:00
parent fc148ee2a0
commit 4876408cba
2 changed files with 14 additions and 9 deletions

View File

@ -2,7 +2,7 @@ import { router } from '../router';
import { Env } from '../[[path]]' import { Env } from '../[[path]]'
import { json } from 'itty-router-extras'; import { json } from 'itty-router-extras';
import StatusCode, { Ok, Fail, Build, ImgItem, ImgList, ImgReq, Folder, AuthToken, FailCode, NotAuth } from "../type"; import StatusCode, { Ok, Fail, Build, ImgItem, ImgList, ImgReq, Folder, AuthToken, FailCode, NotAuth } from "../type";
import { checkFileType, getFileName, parseRange } from '../utils' import { checkFileType, getFilePath, parseRange } from '../utils'
import { R2ListOptions } from "@cloudflare/workers-types"; import { R2ListOptions } from "@cloudflare/workers-types";
const auth = async (request: Request, env: Env) => { const auth = async (request: Request, env: Env) => {
@ -103,11 +103,11 @@ router.post('/upload', auth, async (req: Request, env: Env) => {
continue continue
} }
const time = new Date().getTime() const time = new Date().getTime()
const filename = await getFileName(fileType, time) const objecPath = await getFilePath(fileType, time)
const header = new Headers() const header = new Headers()
header.set("content-type", fileType) header.set("content-type", fileType)
header.set("content-length", `${item.size}`) header.set("content-length", `${item.size}`)
const object = await env.PICX.put(filename, item.stream(), { const object = await env.PICX.put(objecPath, item.stream(), {
httpMetadata: header, httpMetadata: header,
}) as R2Object }) as R2Object
if (object || object.key) { if (object || object.key) {

View File

@ -38,11 +38,16 @@ export function checkFileType(val : string) : boolean {
} }
// 获取文件名 // 获取文件名
export async function getFileName(val : string, time : number) : Promise<string> { export async function getFilePath(val: string, time: number): Promise<string> {
const types = supportFiles.filter(it => it.type === val) const types = supportFiles.filter(it => it.type === val)
if (!types || types.length < 1) { if (!types || types.length < 1) {
return val return val
} }
const rand = Math.floor(Math.random() * 100000) const rand = Math.floor(Math.random() * 100000)
return randomString(time + rand).concat(`.${types[0].ext}`) const fileName = randomString(time + rand).concat(`.${types[0].ext}`)
let date = new Date()
const year = date.getFullYear() //获取完整的年份(4位)
const month = date.getMonth() + 1 //获取当前月份(0-11,0代表1月)
return "/" + year + "/" + month + "/" + fileName
} }