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-20 18:01:55 浏览: 68
auto-modify-the-file-names.zip_names
Sure, here's an updated version of the `getfile.py` script that allows the user to enter a custom file name:
```python
#!/usr/bin/env python
import cgi, os
# Set up the form and get user input
form = cgi.FieldStorage()
fileitem = form['file1']
filename = form['fn'].value
# Check if the file was uploaded
if fileitem.filename:
# Set the path to save the uploaded file
path = os.path.join(os.getcwd(), 'uploads', filename)
# Save the uploaded file to the specified path
with open(path, 'wb') as f:
f.write(fileitem.file.read())
# Print a success message
print('Content-Type: text/html')
print()
print('<h1>File {} uploaded successfully!</h1>'.format(filename))
else:
# Print an error message if no file was uploaded
print('Content-Type: text/html')
print()
print('<h1>No file uploaded!</h1>')
```
To use this script, you would need to create an HTML form with the three data controls mentioned in the prompt:
```html
<form method="post" enctype="multipart/form-data" action="getfile.py">
<label for="file1">Select a file to upload:</label>
<input type="file" name="file1" id="file1"><br>
<label for="fn">Save file as:</label>
<input type="text" name="fn" id="fn"><br>
<input type="submit" name="submit" value="Upload">
</form>
```
In this form, the user can select a file to upload using the `file1` input control, enter a custom file name using the `fn` input control, and submit the form using the `submit` button. When the form is submitted, the `getfile.py` script will receive the file and file name data, and save the uploaded file to the specified path using the custom file name.
阅读全文