Python Requests POST / 上传图像文件

huangapple go评论66阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月14日 04:37:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定