简体   繁体   English

我正在尝试在 typescript 中使用 multer 我想上传一个文件但我的身体是空的 请告诉我如何修复它

[英]i am trying to use multer in typescript i want to upload a file but my body is empty please tell me how to fix it

server.ts服务器.ts

const server = express()
      server.use(bodyParser.json({ limit: '10mb' }));
      server.use(bodyParser.urlencoded({ extended: true }));
      server.use(bodyParser.json())
      server.use(acl);
      server.use(cookieSession({
        name: 'session',
        keys: [config.jwtSecret],
        maxAge: 312460601000, // 31 days
      }));
    
      server.use(responses);
      server.use(scopePerRequest(container));
      const files = 'controllers/**/*.ts';
      server.use(loadControllers(files, { cwd: __dirname }));
    
      server.all('*', (req, res) => {
        return handle(req, res)
      })
    
    
      server.use(express.json());
      server.use(express.urlencoded({ extended: true }));
    
      startDataBase()
    
      server.listen(config.port, () => {
        console.log(`> Ready on http://localhost:${config.port}`)
      })

UploadController上传控制器

import BaseContext from '../BaseContext';
import express from 'express'
import { Request, Response } from 'express';
import { route, GET, POST, DELETE, PATCH, before } from 'awilix-express';
import multer, { FileFilterCallback } from "multer"

type DestinationCallback = (error: Error | null, destination: string) => void
type FileNameCallback = (error: Error | null, filename: string) => void

export const fileStorage = multer.diskStorage({
  destination: (
    request: Request,
    file: Express.Multer.File,
    callback: DestinationCallback
  ): void => {
    callback(null, __dirname + '/uploads/')
  },

  filename: (
    req: Request,
    file: Express.Multer.File,
    callback: FileNameCallback
  ): void => {
    callback(null, Date.now() + '-' + file.originalname)
  }
})

export const fileFilter = (
  request: Request,
  file: Express.Multer.File,
  callback: FileFilterCallback
): void => {
  if (
    file.mimetype === 'image/png' ||
    file.mimetype === 'image/jpg' ||
    file.mimetype === 'image/jpeg'
  ) {
    callback(null, true)
  } else {
    callback(null, false)
  }
}


const upload = multer({ storage: fileStorage });


@route('/api/upload')
export default class Upload extends BaseContext {


  @POST()
  @before(upload.array("files"))
  @route('/file')
  save(req: any, res: Response) {
    console.log(req.files)
    console.log(req.body)
    res.json({ message: "Successfully uploaded files" });

  }

}

file.tsx文件.tsx

export interface MyState {


    files: any,

}

class Test extends React.Component<MyProps, MyState> {

    constructor(props) {
        super(props);
        this.state = {
            files: {}

        };

        this.handleClick = this.handleClick.bind(this);
        this.handleChange = this.handleChange.bind(this)
    
    };

    handleChange(event) {
        this.setState({ files: event.target.files[0] })
    }

    handleClick(event) {

        let fullUrl = 'http://localhost:3000' + '/' + 'api/upload/file';
        const params: any = {
            method: 'POST',
            headers: {
                Authorization: 'bearer',
             

            },
        };

        const formData = new FormData();
        formData.append("files", this.state.files);


        params['headers']['content-type'] = 'multipart/form-data; boundary={boundary string}';
        params['body'] = formData;
        console.log(params)
        return fetch(fullUrl, params)
            .then((res) => console.log(res))
            .catch((err) => (err));

    render() {
        return (
            <div>
                <h1>Upload file</h1>
                <div>
                    <label>Файл</label><br />
                    <input type="file" name="filedata" onChange={this.handleChange} /><br /><br />
                    <button type="button" onClick={this.handleClick}>
                        Кнопка
                    </button>
                </div>
            </div>
        );
    }
}
export default Test;

I have reviewed many articles, and everything is mostly in js, I can't understand how to implement it correctly, no matter what I make my body empty, I think that there should be some other callback in @before看了很多文章,大部分都是用js,看不懂怎么正确实现,不管怎么让body空,我觉得@before里面应该还有一些其他的回调

Maybe I'm somehow transferring the file wrong, I tried without converting it, then in json format, I stopped at formData, but my body is still empty也许我以某种方式传输文件错误,我尝试不转换它,然后在 json 格式,我停在 formData,但我的身体仍然是空的

I use multer this way hope it helps you better understand how to implement it with your project:我以这种方式使用 multer,希望它可以帮助您更好地了解如何在您的项目中实现它:

import multer from "multer";

const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 1000000000, files: 1 },
  fileFilter(req, file, cb) {
    if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
      return cb(new Error("Please upload a valid image file"));
    }
    cb(null, true);
  },
});

app
  .post(
    "/",
    upload.single("image"), // or upload single for one file only
    async (req: Request, res: Response, next: NextFunction) => {

      const image = req.file;
 
      res.json({ message: "hello" });
    }
  )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我想知道如何在 highcharts 中使用 onclick() 函数和符号我在 angular 中使用它。请告诉我 - I want to know how to use the onclick() function and symbol in highcharts Iam using it in angular.Tell me please 我想更新一个.json文件,请告诉我该怎么做 - I want to Update a .json file please tell me how to go about it 我想将我从多个下拉框中选择的值显示到禁用的文本字段中,但无法执行。 请告诉我我在想什么 - I want to display my selected values from a multi dropbox into a disabled text field but I am unable to do it. Please tell me what i am missing 我的 discord 机器人出现错误,请告知如何修复 - i an getting an error in my discord bot, please tell how fix 我可以在 html 表单输入字段中显示我的文本文件数据吗? 如果是,请告诉我怎么做? - can i display my text file data in html form input field? if yes, please tell me how? 我正在尝试在 class 的帮助下打印已定义多边形的周长,但它给了我未定义为 output 请告诉我问题出在哪里 - I am trying to print perimeter of defined polygons with the help of class but it is giving me undefined as an output please tell me where the problem 如果我不使用 multer,ExpressJS 请求正文为空 - ExpressJS request body is empty if i don't use multer 我想上传 1 个文件并克隆到 3 个文件,如何在 nodejs 中使用 multer 将多个文件大小上传到服务器 - I want to upload 1 file and clone to 3 files and how do I upload multiple file sizes to the server using multer in nodejs 我正在尝试接收视频文件并将其与multer一起保存在服务器上 - I am trying to receive video file and save it on the server with multer 如何实现文件上传的恢复暂停功能? 我正在使用 node.js、gridfs 和 multer - How to implement a resume pause functionality for file upload ? I am using node js, gridfs and multer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM