如何使用javascript fetch api上传图片并表达multer [英] How to upload image using javascript fetch api and express multer

查看:72
本文介绍了如何使用javascript fetch api上传图片并表达multer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在reactjs应用程序中工作,我必须上传用户图像。我在文件输入的onChange事件上获取文件并传递它父组件,父组件将使用数据发出请求

I am working in a reactjs application where i have to upload user image. I am getting file on onChange event of file input and passing it parent component and parent component will make a post request using the data

服务器端我正在使用express和multer for文件上传和客户端使用fetch api上传图片。

Server side I am using express and multer for file upload and client side using fetch api to upload the image.

提前致谢:)

推荐答案

我想出来
要将文件/图像上传到multer我们需要一个表单enctype =multipart / form-data,而不用它就不能使用multer

I figure it out To upload an file/image to multer we need a form enctype="multipart/form-data" without that it wont work with multer

我从子组件获取文件然后
1)当我收到时,我创建了一个空格式,其中encType =mutipart / form-data
2)我创建一个新的FormData文件(参考myform)
3)然后在formData
中追加键和值4)创建fetch.post()并且它可以工作:)

I am getting file from a child component then 1) i have created a empty form with the encType="mutipart/form-data" 2) when i received the file i create a new FormData(with ref to myform) 3) then append key and value in the formData 4) create fetch.post() and it works :)

用于参考提交代码

React Parent组件Upload.js

import React, { Component } from 'react'

import { ImageWithoutForm } from "../app/components/ImageUpload";


export default class UploadFile extends Component {
    onImageLoad(e){
        console.log('onImageLoad', e.target.files[0]);
        this.uploadForm(e.target.files[0]);
    }

    uploadForm(file){
        let form = new FormData(this.refs.myForm);
        form.append('myImage', file);
        fetch('/upload-image', {
          method: 'POST',
          body: form
        }).then(res => console.log('res of fetch', res));
    }

  render() {
    return (
      <div>
        <h4>Upload Image</h4>
        <ImageWithoutForm onImageLoad={(e)=>this.onImageLoad(e)} />
        <form id="upload_form" ref="myForm"  encType="multipart/form-data">
        </form>
      </div>
    )
  }
}

带有输入的React Child Component加载文件ImageWithoutForm.js

import React, { Component } from 'react'

export  class ImageWithoutForm extends Component {

    handleSubmit(e){
        this.props.onImageLoad(e);
    }


  render() {
    return (
      <div>
            <input type="file" onChange={(e)=>this.handleSubmit(e)}/>
      </div>
    )
  }
}

从某人github repo和自定义UploadImage.js获取的Express Route文件

const express = require('express');
const multer = require('multer');
const path = require('path');

// Set Storage Engine
const storage = multer.diskStorage({
  destination: './public/uploads/',
  filename: function(req, file, cb){
    cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

// Init Upload
const upload = multer({
  storage: storage,
  limits:{fileSize: 1000000},
  fileFilter: function(req, file, cb){
    checkFileType(file, cb);
  }
}).single('myImage');

// Check File Type
function checkFileType(file, cb){
  // Allowed ext
  const filetypes = /jpeg|jpg|png|gif/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);

  if(mimetype && extname){
    return cb(null,true);
  } else {
    cb('Error: Images Only!');
  }
}

// Init app
const app = express.Router();


// Public Folder
app.use(express.static('./public'));


app.post('/', (req, res) => {
    console.log('handling upload image');
  upload(req, res, (err) => {
    if(err){
      console.log('first err', err);
      res.send({
        msg: err
      });
    } else {
      if(req.file == undefined){
        console.log('Error: No File Selected!')
        res.send({
          msg: 'Error: No File Selected!'
        });
      } else {
        console.log('File Uploaded!')
        res.send({
          msg: 'File Uploaded!',
          file: `uploads/${req.file.filename}`
        });
      }
    }
  });
});

module.exports = app;

在我的快递app.js中只需要路线文件ImageUpload.js

and in my express app.js just require the route file ImageUpload.js

并映射到这样的路线

var uploadImage = require('./routes/UploadImage');
server.use('/upload-image', uploadImage);

这篇关于如何使用javascript fetch api上传图片并表达multer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆