1.React文件上传组件github地址: https://github.com/SoAanyip/React-FileUpload
2.Util里边新建file-uploader文件夹,里边新建index.jsx
- import React from ‘react‘;
- import FileUpload from ‘./react-fileupload.jsx‘;
- class FileUploader extends React.Component{
- render(){
- const options={
- baseUrl :‘/manage/product/upload.do‘,
- fileFieldName : ‘upload_file‘,
- dataType : ‘json‘,
- chooseAndUpload : true,
- uploadSuccess : (res) => {
- this.props.onSuccess(res.data);
- },
- uploadError : (err) => {
- this.props.onError(err.message || ‘上传图片出错啦‘);
- }
- }
- return (
- <FileUpload options={options}>
- <button className="btn btn-xs btn-default" ref="chooseAndUpload">请选择图片</button>
- </FileUpload>
- )
- }
- }
- export default FileUploader;
3.在save.jsx里边使用FileUploader组件
- <div className="form-group">
- <label className="col-md-2 control-label">商品图片</label>
- <div className="col-md-10">
- {
- this.state.subImages.length ? this.state.subImages.map(
- (image, index) => (
- <div className="img-con" key={index}>
- <img className="img" src={image.url} />
- <i className="fa fa-close" index={index} onClick={(e) => this.onImageDelete(e)}></i>
- </div>)
- ) : (<div>请上传图片</div>)
- }
- </div>
- <div className="col-md-offset-2 col-md-10 file-upload-con">
- <FileUploader onSuccess={(res) => this.onUploadSuccess(res)}
- onError={(errMsg) => this.onUploadError(errMsg)}/>
- </div>
- </div>
4.图片上传成功后执行nUploadSuccess函数,更新state里边subImages数据
- //上传图片成功
- onUploadSuccess(res){
- let subImages = this.state.subImages;
- subImages.push(res);
- this.setState({
- subImages : subImages
- });
- }
5.删除图片
- // 删除图片
- onImageDelete(e){
- let index = parseInt(e.target.getAttribute(‘index‘)),
- subImages = this.state.subImages;
- subImages.splice(index, 1);
- this.setState({
- subImages : subImages
- });
- }
原文地址:https://www.cnblogs.com/wangyawei/p/9230955.html
时间: 2024-10-10 20:57:20