Prerequisites
Before we dive into the code, ensure you have the following.
- Basic knowledge of ReactJS and Python
- Node.js and npm installed for ReactJS development
- AWS account with S3 bucket set up
ReactJS Frontend
We'll start by creating a simple ReactJS component that allows users to select and upload a document.
// FileUploadComponent.jsx
import React, { useState } from 'react';
const FileUploadComponent = () => {
const [file, setFile] = useState(null);
const handleFileChange = (event) => {
setFile(event.target.files[0]);
};
const handleUpload = () => {
const formData = new FormData();
formData.append('file', file);
fetch('http://your-backend-api/upload', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
console.log('Upload successful:', data);
})
.catch(error => {
console.error('Error uploading file:', error);
});
};
return (
<div>
<input type="file" onChange={handleFileChange} />
<button onClick={handleUpload}>Upload</button>
</div>
);
};
export default FileUploadComponent;
Python Backend with Flask and Boto3
Next, let's create a Python backend using Flask and Boto3 to handle the document upload.
# app.py
from flask import Flask, request, jsonify
import boto3
from botocore.exceptions import NoCredentialsError
app = Flask(__name__)
# Configure AWS credentials
AWS_ACCESS_KEY = 'your_access_key'
AWS_SECRET_KEY = 'your_secret_key'
S3_BUCKET = 'your_s3_bucket'
# AWS S3 configuration
s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY)
@app.route('/upload', methods=['POST'])
def upload_file():
try:
file = request.files['file']
s3.upload_fileobj(file, S3_BUCKET, file.filename)
return jsonify({'message': 'File uploaded successfully'}), 200
except NoCredentialsError:
return jsonify({'error': 'AWS credentials not available'}), 500
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)
Conclusion
By combining ReactJS for the front end and Python with AWS Boto3 for the back end, you've created a robust document upload feature for your web application.