【问题标题】:Getting wrong image URL when uploading image using node js and react js使用 node js 和 react js 上传图像时获取错误的图像 URL
【发布时间】:2018-06-26 22:04:03
【问题描述】:

E:oomsack/Images/idea.png ,

反应代码

import React, { Component } from 'react';
import './add_new.css';
import axios from 'axios';
import { Redirect } from 'react-router';
import Header from '../header/Header.js';
import Footer from '../footer/Footer.js';

class Add_new extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      imageURL: '',
      username:'',
      usersurname:''
    };

    this.handleUploadImage = this.handleUploadImage.bind(this);
  }

  handleUploadImage(ev) {
    ev.preventDefault();

    const data = new FormData();
    data.append('file', this.uploadInput.files[0]);
    data.append('filename', this.uploadInput.value);
    data.append('username', this.username.value);
    data.append('usersurname', this.usersurname.value);

    fetch('http://localhost:2000/users', {
      method: 'POST',
      body: data,
    }).then((response) => {
      response.json().then((body) => {
        this.setState({ imageURL: `http://localhost:2000/${body.file}` });
        console.log(response);
      });
    });
  }

  render() {
    return (
      <div>
      <Header />
      <form onSubmit={this.handleUploadImage} style={{ padding:"80px"}}>
        <div>
          <input ref={(ref) => { this.uploadInput = ref; }} type="file" />
        </div>
        <div>
          <input ref={(ref) => { this.username = ref; }} type="text" placeholder="Enter name" />
        </div>
        <br />
        <div>
          <input ref={(ref) => { this.usersurname = ref; }} type="text" placeholder="Enter surname" />
        </div>
        <br />
        <div>
          <button>Upload</button>
        </div>
        <img src={this.state.imageURL} alt="img" />
      </form>
      <Footer />
      </div>
    );
  }
}

export default Add_new;

快递代码

const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
const cors = require('cors');
var mysql = require('mysql');
const app = express();

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database:"db_database"
});


app.use(logger('dev'));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(fileUpload());
app.use('/Images', express.static(__dirname + '/Images'));


app.post('/users', (req, res, next) => {
  console.log(req);
  let imageFile = req.files.file;
  let path = `${__dirname}/Images/${imageFile.name}`;
  console.log(path);
  imageFile.mv(path, function(err) {
    if (err) {
      return res.status(500).send(err);
    }
    con.query("INSERT INTO webtable (username,filename,usersurname) VALUES ('"+req.body.username+"','"+path+"','"+req.body.usersurname+"')", function(err, results) {  
      console.log(results); 
      res.json({file: `Images/${req.body.filename}.jpg`});
    });
  });
})

我得到这个 => Images/C:\fakepath\image_name.png.jpg 在浏览器控制台的网络选项卡中。 虽然我的源地址是 E:\rooms\back/Images/image_name.png

【问题讨论】:

    标签: node.js reactjs file-upload


    【解决方案1】:

    您已经在代码中使用了正确的字段名称,您想要什么预期结果?您可以发送以下内容

    res.json({file: `/Images/${imageFile.name}`});
    

    res.json({file: path});
    

    更新:

    使用`而不是'

        con.query("INSERT INTO webtable (username,filename,usersurname) VALUES ('"+req.body.username+"',`"+path+"`,'"+req.body.usersurname+"')", function(err, results) {  
          console.log(results); 
          res.json({file: `Images/${req.body.filename}.jpg`});
        });
    

    【讨论】:

    • 先生,实际上保存在数据库中的数据是 E:oomsack/Images/header.jpg 而我需要像这样保存 E:\rooms\back\Images\header.jpg
    • 先生,完成此操作后,图像在文件夹中移动正常,但任何数据都没有插入数据库中
    • 一件事我还不能得到,为什么'r'丢失并且'b'在插入数据库时​​转换为方形框,而我在控制台获得正确的url。
    猜你喜欢
    • 2021-12-09
    • 2018-10-24
    • 2014-02-15
    • 1970-01-01
    • 2021-05-15
    • 2020-10-06
    • 2019-11-30
    • 2019-01-13
    • 2016-12-01
    相关资源
    最近更新 更多