Загрузить файл с помощью ReactJS через плагин BlueImp FileUpload jQuery
Это новичок в ReactJS.
Может ли кто-нибудь прокомментировать, что использовать или как иметь форму (с несколькими полями ввода и селектором файлов), будет загружен в React?
Разрушали мои нервы, пытаясь использовать плагин BlueImp JQuery-file-upload. Сообщения об ошибках являются загадочными и не получили никакой полезной помощи от Google.
Мой код выглядит следующим образом:
<form id="myForm" enctype="multipart/form-data" onSubmit={this.handleSubmit}>
<input type="text" name="name">
<input type="text" name="lastName">
<input type="file" accept="image/*" name="myPic">
</form>
// Inside handleSubmit() of my component
$('#myForm").fileupload('add', {url: "myurl"});
Спасибо!
Ответы
Ответ 1
Использование плагина jQuery внутри React разумно, но поскольку React сохраняет свое собственное виртуальное представление DOM, вам следует избегать использования селекторов jQuery.
Используйте цель события, чтобы получить ссылку на реальный DOM node, когда ваша форма отправлена, и заверните ее в объект jQuery для доступа к плагину:
React.createClass({
handleSubmit: function(event) {
$(event.target).fileupload('add', {url: "myurl"});
},
render: function() {
return (
<form enctype="multipart/form-data" onSubmit={this.handleSubmit}>
<input type="text" name="name" />
<input type="text" name="lastName" />
<input type="file" accept="image/*" name="myPic" />
</form>
);
}
});
Ответ 2
Я попробовал BlueImp, но сдался, и я использую решение, измененное из здесь, чтобы сделать это:
/** @jsx React.DOM */
var FileForm = React.createClass({
getInitialState: function() {
return {data_uri: null}
},
handleSubmit: function() {
$.ajax({
url: url,
type: "POST",
data: this.state.data_uri,
success: function(data) {
// do stuff
}.bind(this),
error: function(xhr, status, err) {
// do stuff
}.bind(this)
});
return false;
},
handleFile: function(e) {
var reader = new FileReader();
var file = e.target.files[0];
reader.onload = function(upload) {
this.setState({
data_uri: upload.target.result
});
console.log(this.state.data_uri)
}.bind(this);
reader.readAsDataURL(file);
},
render: function() {
return (
<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<input type="file" onChange={this.handleFile} />
<input type="submit" value="Submit />
</form>
);
}
});
Оттуда ваша конечная точка должна быть в состоянии справиться с ней.
Ответ 3
Чтобы использовать плагин BlueImp JQuery-file-upload с ReactJS, вам необходимо установить для параметра replaceFileInput
значение false. Это происходит потому, что когда replaceFileInput
истинно (по умолчанию), BlueImp заменяет элемент ввода файла новым при каждом выборе нового файла.. и это то, что ReactJS не нравится.
Об этом узнали из:
https://groups.google.com/d/msg/reactjs/lXUpL22Q1J8/-ibTaq-OJ6cJ
Смотрите документацию на replaceFileInput
здесь:
https://github.com/blueimp/jQuery-File-Upload/wiki/Options#replacefileinput
Ответ 4
Здесь мой способ NO jQuery, используя Parse.com
var UploadImageForm = React.createClass({
getInitialState: function() {
return {
myFileName: "",
myFileHandle: {}
};
},
handleChange: function(event) {
console.log("handleChange() fileName = " + event.target.files[0].name);
console.log("handleChange() file handle = " + event.target.files[0]);
this.setState( {myFileName: event.target.files[0].name} );
this.setState( {myFileHandle: event.target.files[0]} );
},
handleSubmit: function(e) {
e.preventDefault();
console.log("INSIDE: handleSubmit()");
console.log("fileName = " + this.state.myFileName);
console.log("this.state.myFileHandle = " + this.state.myFileHandle);
if (this.state.myFileHandle) {
console.log("INSIDE if test myFileHandle.length");
var file = this.state.myFileHandle;
var name = this.state.myFileName;
var parseFile = new Parse.File(name, file);
var myUser = new Parse.Object("TestObj");
myUser.set("profilePicFile", parseFile);
myUser.save()
.then(function() {
// The file has been saved to User.
this.setState( {myFileHandle: null} );
console.log("FILE SAVED to Object: Parse.com");
}.bind(this), function(error) {
// The file either could not be read, or could not be saved to Parse.
console.log("ERROR: Parse.com " + error.code + " " + error.message);
});;
} // end if
},
render: function() {
return (
<form onSubmit={this.handleSubmit}>
<input type="file" onChange={this.handleChange} id="profilePhotoFileUpload" />
<input type="submit" value="Post" />
</form>
);
}
});
Ответ 5
Здесь моя:
Было бы просто изменить для обработки нескольких файлов или использовать собственный XHR вместо jQuery.
var FileUpload = React.createClass({
handleFile: function(e) {
var file = e.target.files[0];
var formData = new FormData();
formData.append('file', file, file.name);
$.ajax({
url: URL,
data: formData,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function(data) {
console.log('success', data);
},
error: function() {
console.error('error uploading file');
},
});
},
render: function() {
return (
<input className="btn btn-default btn-file" type="file" onChange={this.handleFile} accept="image/*;capture=camera"/>
);
}
});