gpt4 book ai didi

node.js - React 和 Node js 中的文件上传不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 01:57:49 25 4
gpt4 key购买 nike

我正在努力上传文件,但无法找到明确的解决方案。我尝试了很多方法但不起作用。现在控制台显示 200 并显示文件已上传但文件未进入文件夹的消息。我已经检查了文件大小限制和文件夹是否正常,但不知道为什么它不起作用。请问有什么帮助吗?

/// react 组件

 import { saveBasicUser, getOneBasicUser, uploadFile } from 
'../../actions/basicAction';

this.state = { file: []};

handleChange(event) {

this.setState({
[event.target.name]: event.target.value,
file:
event.target.files})
}

handleSubmit(event) {
event.preventDefault();
var file = this.state.file

let formData = new FormData();
formData.append('file', file);

// console.log(obj);
console.log(formData);

// this.props.dispatch(saveBasicUser(obj ))
this.props.dispatch(uploadFile(formData ))
}


<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<input type="file" name = "file" onChange={this.handleChange} />
<button type="submit" className="btn btn-success btn-lg">Submit</button>

//////// Action 部分

 export function uploadFile(formData) {
console.log(formData)
return (dispatch) => {

return axios.post('/upload_file', {
headers: { 'content-type': 'multipart/form-data' },
data: formData
}).then(function (res) {

console.log(res)
}).catch(function (err) {
console.log(" err")
console.log(err)
})
}
}

//////服务器部分

var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname))
}
})


var upload = multer({ storage: storage, limits: {fileSize : 1000000} }).single('file');


app.post('/upload_file', function(req, res){

upload(req, res, function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});

});

最佳答案

我终于找到了解决办法。

react JS

import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import Messages from '../Messages';
import classnames from 'classnames';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { getOneBasicUser ,uploadFile} from '../../actions/basicAction';
//--------------------------------------------------------------------------
class Upload extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};


this.handleChange = this.handleChange.bind(this);
this.handleFile = this.handleFile.bind(this);
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------------
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
//--------------------------------------------------------------------------
handleFile(e) {

e.preventDefault();

var id = this.props.params.id;

console.log(id);

var formData = new FormData($('form')[0]);

var isFileExist = !!$('input[type=file]')[0].files[0];



if (isFileExist) {

$.ajax({

url: '/upload_file/'+ id,

type: 'POST',

data: formData,

xhr: function () {

var xhr = new window.XMLHttpRequest();

xhr.upload.addEventListener("progress", function (e) {

if (e.lengthComputable) {

$('progress').attr({value: e.loaded, max: e.total});

$('#status').empty().text(parseInt((e.loaded / e.total * 100)) + '%');

}

}, false);

return xhr;

}.bind(this),

success: function (data) {

this.setState({

data: data

});

$('#status').empty().text('File Uploaded!');

}.bind(this),

error: function (xhr, status, err) {

console.log( err);

}.bind(this),

cache: false,

contentType: false,

processData: false

});

} else {

$('#status').empty().text('Please choose the file.');

}

}
//--------------------------------------------------------------------------
render() {




return (
<div className="container ca-container">
<div className="row">
<div className="col-md-12">
<h2> Upload File </h2>
<hr />
</div>
</div>
<form onSubmit={this.handleFile} encType="multipart/form-data">
<div className="row">
<div className="col-md-12">
<div className="col-md-6">
<h3 id="status" className ="label label-success"></h3>
<div className="form-group">
<label>
Name:
</label>
<input type="file" className="form-control" name="BasicUserFile" onChange={this.handleChange} placeholder="file" />
</div>
<div className="btn-group" role="group">
<button type="submit" value="Upload File" className="btn btn-success btn-lg">Upload</button>
</div>
</div>

</div>
</div>
</form>
</div>
);
}



}
// ======================== REDUX CONNECTORS ========================
const mapStateToProps = (state) => {
return {
//basicUser: state.basicUser.basicUser

};
};

export default connect(mapStateToProps)(Upload);

////server.js

var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads')
},
filename: function (req, file, cb) {
var basic_id = req.params.id
cb(null, file.fieldname + '-' + basic_id+ path.extname(file.originalname))
}
})


var upload = multer({ storage: storage, limits: {fileSize : 1000000} }).single('BasicUserFile');


app.post('/upload_file/:id', function(req, res){

console.log("000000000000000000000000000000000000000000000000")

console.log(req.params)

console.log("000000000000000000000000000000000000000000000000")




upload(req, res, function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});

});

关于node.js - React 和 Node js 中的文件上传不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47248282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com