routing-controllers
routing-controllers copied to clipboard
question: <How to upload multi files of different fields>
I was trying to upload multi pictures with both the origin files and compressed blob named "picFile" and "thumbUrl"
let fd = new FormData();
for (let file of fileList.value) {
fd.append("picFile", file.originFileObj); // file
/* let thumbUrl = compress(file.thumbUrl)
console.log(thumbUrl) */
fd.append("thumbUrl", file.originFileObj); // blob ,changed to originFileObj is the same result
}
@Post("/upload")
async uploadPic(@Body({ required: true }) picInfo: any, @UploadedFiles("picFile") picFile: any, @UploadedFiles("thumbUrl") thumbUrl: any): Promise<any> {}
allowHeaders: ["Content-Type", "Authorization", "Accept","X-Requested-With","content-type", "authorization"]
The problem: if I upload both "picFile" and "thumbUrl" got an CORS error "Access to XMLHttpRequest at 'http://localhost:3001/apis/upload?timestamp=1613804673403' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." if I delete "picFile" or "thumbUrl" , I can upload success.
use multer option is the same result
// fileUploadOptions
export default {
storage: multer.diskStorage({
destination: (req: any, file: any, cb: any) => {
cb(null, "public/uploads/");
},
filename: (req: any, file: any, cb: any) => {
const fileFormat = file.originalname.split(".");
// cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
cb(null, file.originalname);
}
}),
fileFilter: (req: any, file: any, cb: any) => {
if (!/image/.test(file.mimetype)) {
return cb(null, false, new Error("I don't have a clue!"));
}
cb(null, true);
},
limits: {
fieldNameSize: 255,
fileSize: 1024 * 1024 * 5
}
};
@Post("/upload")
async uploadPic(@Body({ required: true }) picInfo: any, @UploadedFiles("picFile", { options: fileUploadOptions }) picFile: any,@UploadedFiles("thumbUrl") thumbUrl: any): Promise<any> {}
I used this signature to manage multiple file uploads:
async createProject(@BodyParam('id_project') id_project: number, @BodyParam('projectName') projectName: string, @Req() req: Request, @Res() res: Response): Promise<Project | Response<any>> {
const exportFile = (req.files as any).export[0];
const listFile = (req.files as any).list[0];
log.info('create / update project file upload: ' + exportFile.originalname);
my cors settings:
const routingControllersOptions = {
routePrefix: '/api',
cors: true,
controllers: [
__dirname + '/controllers/*.js',
],
middlewares: [
StrictTransportSecurityMiddleware,
BodyParserJsonMiddleware,
BodyParserUrlEMiddleware,
LuscaSameOriginMiddleware,
LuscaXSSProtectionMiddleware
],
authorizationChecker: AuthController.authChecker,
currentUserChecker: AuthController.getCurrentUser,
validationOptions: { skipMissingProperties: true }
};
hope this helps