简体   繁体   中英

Saving image from response object as file in python

I'm trying to retrieve and save to file a jpg.

from shareplum import Site
from shareplum import Office365
from shareplum.site import Version

server_url = "https://xxx.sharepoint.com/"
site_url = "sites/Technicians/"

un = "un"
pw = "pw"

authcookie = Office365(server_url, username=un, password=pw).GetCookies()
site = Site(server_url + site_url, version=Version.v2016, authcookie=authcookie)

folder = site.Folder('Shared Documents/Technical client documentation' \
                     '/Clients/TestAccount/Pictures')
p = folder.get_image('test.jpg')

Relevant code from the library. I've added get_image. I used this article as reference.

    def get_file(self, file_name):
        response = self._session.get(self.site_url + f"/_api/web/GetFileByServerRelativeUrl('{self.info['d']['ServerRelativeUrl']}/{file_name}')/$value")
        return response.text


    def get_image(self, file_name):
        response = self._session.get(self.site_url + f"/_api/web/GetFileByServerRelativeUrl('{self.info['d']['ServerRelativeUrl']}/{file_name}')/$value")
        if response.status_code== 200:
            with open('/home/bruce/test_scripts/pictestNew.jpg', 'wb') as f:
#                r.raw.decode_content = True
                shutil.copyfileobj(response.raw, f)
        return "ok"

Works fine with text files. Also, if I do a print(response.text) you get what you'd expect to see if you tried to open a binary image file in a text editor.

Doing it as above the file was created, but empty. No errors.

I did try returning the text and then writing that directly to a file.

p = folder.get_image('test.jpg')
p = bytearray(p)

P would be the returned response.text then:

with open('picOut1.jpg', 'wb') as f:
    f.write(p)

That got me an image file of the correct size but trying to view got me

Error interpreting JPEG image file (Not a JPEG file: starts with 0xef 0xbf

Searching for that led me to the linked article and the other attempt. I know the data is there I just don't know how to get it saved.

For downloading an image via python, shareplum and the rest api this works.

This was added to folder.py inside of shareplum. Which for me is in my venv folder under libraries.

def get_image(self, file_name):
    response = self._session.get(self.site_url + f"/_api/web/GetFileByServerRelativeUrl('{self.info['d']['ServerRelativeUrl']}/{file_name}')/$value")
    #print(response)
    if response.status_code== 200:
        with open('/home/bruce/test_scripts/testFriday1.jpg', 'wb') as f:
            f.write(response.content)
    return "ok"

File is written and viewable with no errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM