0% found this document useful (0 votes)
7 views

Text

Uploaded by

moe.montaser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Text

Uploaded by

moe.montaser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

To handle large file uploads and prevent the page from changing or timing out, we

can use AJAX for the file upload process. This way, the upload happens
asynchronously, and you get feedback on the progress without navigating away from
the upload page.

Here's the updated solution:

1. **Update `app.py`**:
Ensure the Flask application can handle large file uploads and returns a JSON
response.

```python
from flask import Flask, request, jsonify
import os

app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024 * 1024 # 2 GB

if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)

@app.route('/')
def upload_file():
return render_template('upload.html')

@app.route('/uploader', methods=['POST'])
def uploader():
if 'file' not in request.files:
return jsonify({'error': 'No file part'})
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No selected file'})
if file:
filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(filepath)
return jsonify({'success': f'File successfully uploaded to {filepath}'})
return jsonify({'error': 'File upload failed'})

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
```

2. **Update `upload.html`**:
Use JavaScript (AJAX) to handle the file upload process.

```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Upload File</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Upload File</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="button" value="Upload" onclick="uploadFile()">
</form>
<div id="progress"></div>
<script>
function uploadFile() {
var formData = new FormData();
var fileInput = document.getElementById('file');
var file = fileInput.files[0];
formData.append('file', file);

$.ajax({
url: '/uploader',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('#progress').text('Upload progress: ' + percentComplete + '%');
}
}, false);
return xhr;
},
success: function(data) {
$('#progress').text(data.success || data.error);
},
error: function() {
$('#progress').text('File upload failed');
}
});
}
</script>
</body>
</html>
```

### Explanation:

1. **Flask (`app.py`)**:
- The `MAX_CONTENT_LENGTH` is set to 2 GB to allow large file uploads.
- The `/uploader` endpoint returns a JSON response with success or error
messages.

2. **HTML (`upload.html`)**:
- Includes jQuery for easier AJAX handling.
- The form submission is handled by JavaScript, which sends the file data to the
server using AJAX.
- Displays upload progress and success/error messages without navigating away
from the page.

3. **Running the Flask Application**:


- Follow the same steps as before to run the Flask application with `python
app.py`.

4. **Accessing from iPhone**:


- Ensure your PC and iPhone are on the same network.
- Open the browser on your iPhone and navigate to the IP address of your PC with
port 5000 (e.g., `http://<your-pc-ip>:5000`).

This setup should handle large file uploads more gracefully by providing upload
progress feedback and preventing the page from timing out.

You might also like