Modify the getfile.py used during class to allow user to enter a customized file name instead of fixed original file name. The interface should have three data controls: (1) The file Selector, which can be made by using “input name=file1 type=file ” (2) The saving file name, which can be made by using “input name=fn ” (3) The Submit button, which can be made by “input type=submit name=submit value=Upload ” Don't use template. Submit the python program
时间: 2024-01-14 16:04:46 浏览: 82
auto-modify-the-file-names.zip_names
Sure, here's the modified `getfile.py` script that allows the user to enter a customized file name:
```python
#!/usr/bin/env python3
import cgi
import os
# Set the upload directory
UPLOAD_DIR = '/path/to/upload/directory/'
# Create the form object
form = cgi.FieldStorage()
# Get the uploaded file object
fileitem = form['file1']
# Get the custom file name from the form
filename = form['fn'].value
# Check if the file was uploaded
if fileitem.filename:
# Create the upload directory if it doesn't exist
if not os.path.isdir(UPLOAD_DIR):
os.makedirs(UPLOAD_DIR)
# Set the file path
filepath = UPLOAD_DIR + filename
# Open the file for writing in binary mode
with open(filepath, 'wb') as f:
# Read the file in chunks
while True:
chunk = fileitem.file.read(1024)
if not chunk:
break
# Write the chunk to the file
f.write(chunk)
# Print a success message
print('Content-type:text/html\r\n\r\n')
print('<html>')
print('<head>')
print('<title>File Upload</title>')
print('</head>')
print('<body>')
print('<h2>File Uploaded Successfully</h2>')
print('</body>')
print('</html>')
else:
print('Content-type:text/html\r\n\r\n')
print('<html>')
print('<head>')
print('<title>File Upload Error</title>')
print('</head>')
print('<body>')
print('<h2>Error: No File Specified</h2>')
print('</body>')
print('</html>')
```
This script uses the `cgi` module to handle the form data, and allows the user to enter a custom file name using an additional form input. The custom file name is then used to save the uploaded file to the upload directory.
阅读全文