有人知道如何在Nextjs中设置文件结构来处理多个URL参数吗?
我的网址是:/api/upload?file=${filename}&fileType=${fileType}
我的文件结构是:
app
api
upload
[filename]
[fileType]
route.ts
这是我的理解,这是什么目录应该看起来像,但我得到以下错误:
- error No HTTP methods exported in 'C:\Users\Alex\Documents\GitHub\procore-new\app\api\upload\route.ts'. Export a named export for each HTTP method.
这是我的路线代码:
import S3 from "aws-sdk/clients/s3";
import { NextResponse } from "next/server";
interface IParams {
filename: string;
fileType: string;
}
export async function GET(request: Request, { params }: { params: IParams }) {
const { filename, fileType } = params;
const s3 = new S3({
signatureVersion: "v4",
region: "us-east-2",
accessKeyId: process.env.ACCESS_KEY,
secretAccessKey: process.env.SECRET_KEY,
});
const preSignedUrl = await s3.getSignedUrl("putObject", {
Bucket: process.env.BUCKET_NAME,
Key: filename,
ContentType: fileType,
Expires: 5 * 60,
});
return NextResponse.json({ preSignedUrl });
}
我的前端请求:
"use client";
import axios from "axios";
import { toast } from "react-hot-toast";
const ImageUpload = () => {
const uploadPhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]!;
const filename = file.name;
const fileType = file.type;
console.log(file, filename, fileType);
const res = await axios(
`/api/upload?file=${filename}&fileType=${fileType}`
);
const { url } = await res.data;
const config = {
headers: {
"Content-Type": fileType,
},
};
const upload = await axios.put(url, file, config);
if (upload.status === 200) {
console.log("Uploaded successfully!");
} else {
console.error("Upload failed.");
}
const s3FileUrl = `https://<nextjspractice>.s3.us-east-2.amazonaws.com/${filename}`;
console.log("file url: ", s3FileUrl);
};
return (
<input type="file" accept="image/png, image/jpeg" onChange={uploadPhoto} />
);
};
export default ImageUpload;
我在想也许可以用文件夹上的扩展操作符?也许像[... params],但我不确定,任何帮助都将是惊人的!
1条答案
按热度按时间lhcgjxsq1#
找到解决方案了!
如果您在app/(route)/route.ts中使用[paramName]作为文件结构,并且您有多个参数,则可以执行以下操作:
创建一个文件夹来展开params对象,在我的例子中:[... params]和inside创建标准route.ts文件。
然后在该文件中,像这样解构参数:
这将给予你一个所有参数的数组,对我来说看起来像这样:
另外,在对API的请求中,请确保您的请求如下所示:
其中路由名称后面的每个参数前面都有一个“/”