英文:
Python Requests POST / Upload Image File
问题
import requests, os
imageFile = "test.jpg"
myobj = {'key': 'key', 'submit':'yes'}
up = {'fileToUpload':(imageFile, open(imageFile, 'rb'), 'multipart/form-data')}
r = requests.post('https://website/uploadfile.php', files=up, data = myobj)
sendTo = r.text
os.remove(imageFile)
上述代码生成了以下错误信息:
PermissionError: [WinError 32] 另一个进程正在使用此文件,进程无法访问。
英文:
How can I os.remove() this image after it has been uploaded? I believe that I need to close it somehow.
import requests, os
imageFile = "test.jpg"
myobj = {'key': 'key', 'submit':'yes'}
up = {'fileToUpload':(imageFile, open(imageFile, 'rb'), 'multipart/form-data')}
r = requests.post('https://website/uploadfile.php', files=up, data = myobj)
sendTo = r.text
os.remove(imageFile)
The above generates:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
答案1
得分: 1
你打开文件后从未关闭它。
尝试:
import requests, os
imageFile = "test.jpg"
with open(imageFile, 'rb') as f:
myobj = {'key': 'key', 'submit':'yes'}
up = {'fileToUpload':(imageFile, f, 'multipart/form-data')}
r = requests.post('https://website/uploadfile.php', files=up, data = myobj)
sendTo = r.text
os.remove(imageFile)
英文:
You never closed the file after opening.
Try:
import requests, os
imageFile = "test.jpg"
with open(imageFile, 'rb') as f:
myobj = {'key': 'key', 'submit':'yes'}
up = {'fileToUpload':(imageFile, f, 'multipart/form-data')}
r = requests.post('https://website/uploadfile.php', files=up, data = myobj)
sendTo = r.text
os.remove(imageFile)
答案2
得分: 1
需要重构你的代码,以便使用上下文管理器:
import requests, os
imageFile = "test.jpg"
myobj = {'key': 'key', 'submit':'yes'}
with open(imageFile, "rb") as im:
up = {'fileToUpload': (imageFile, im, 'multipart/form-data')}
r = requests.post('https://website/uploadfile.php', files=up, data=myobj)
sendTo = r.text
os.remove(imageFile)
当退出with
块时,文件将自动关闭,锁将被释放,然后你可以删除它。
英文:
You need to restructure your code so that you are using a context manager:
import requests, os
imageFile = "test.jpg"
myobj = {'key': 'key', 'submit':'yes'}
with open(imageFile, "rb") as im:
up = {'fileToUpload':(imageFile, im, 'multipart/form-data')}
r = requests.post('https://website/uploadfile.php', files=up, data = myobj)
sendTo = r.text
os.remove(imageFile)
When you exit the with
block, the file will automatically be closed, the lock will be released, and you can then delete it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论