references/files-attachments.md
4.3 KB查看排版效果| 1 | # Files & Attachments |
| 2 | |
| 3 | ## Downloading Files |
| 4 | |
| 5 | ```python |
| 6 | # Get raw binary content of an attachment |
| 7 | raw = zot.file('ATTACHMENTKEY') |
| 8 | with open('paper.pdf', 'wb') as f: |
| 9 | f.write(raw) |
| 10 | |
| 11 | # Convenient wrapper: dump file to disk |
| 12 | # Uses stored filename, saves to current directory |
| 13 | zot.dump('ATTACHMENTKEY') |
| 14 | |
| 15 | # Dump to a specific path and filename |
| 16 | zot.dump('ATTACHMENTKEY', 'renamed_paper.pdf', 'papers') |
| 17 | # Create the directory first. Returns None on success, not a path. |
| 18 | ``` |
| 19 | |
| 20 | `dump()` uses the provided filename or stored attachment filename. For responses classified as HTML snapshots, 1.15.2 appends `.zip` to that name; ZIP/EPUB handling can return an archive member. Verify the saved bytes and type instead of assuming every snapshot is a ZIP or is named with its key. Remote `/file` downloads require stored, synced files and appropriate permissions; linked files are not uploaded to Zotero storage. |
| 21 | |
| 22 | ## Finding Attachments |
| 23 | |
| 24 | ```python |
| 25 | # Get child items (attachments, notes) of a parent item |
| 26 | children = zot.children('PARENTKEY') |
| 27 | attachments = [c for c in children if c['data']['itemType'] == 'attachment'] |
| 28 | |
| 29 | # Get the attachment key |
| 30 | for att in attachments: |
| 31 | key = att['data']['key'] |
| 32 | filename = att['data'].get('filename') # absent on linked URLs |
| 33 | content_type = att['data']['contentType'] |
| 34 | link_mode = att['data']['linkMode'] # 'imported_file', 'linked_file', 'imported_url', 'linked_url' |
| 35 | ``` |
| 36 | |
| 37 | ## Uploading Attachments |
| 38 | |
| 39 | **Note**: Upstream still labels attachment helpers beta. The simple/both helpers below require the remote API; local uploads need a manually built attachment dict and Zotero 10+ authorization (see [authentication.md](authentication.md)). |
| 40 | |
| 41 | ```python |
| 42 | # Simple upload: one or more files by path |
| 43 | result = zot.attachment_simple(['/path/to/paper.pdf', '/path/to/notes.docx']) |
| 44 | |
| 45 | # Upload as child items of a parent |
| 46 | result = zot.attachment_simple(['/path/to/paper.pdf'], parentid='PARENTKEY') |
| 47 | |
| 48 | # Upload with custom filenames: list of (name, path) tuples |
| 49 | result = zot.attachment_both([ |
| 50 | ('Paper 2024.pdf', '/path/to/paper.pdf'), |
| 51 | ('Supplementary.pdf', '/path/to/supp.pdf'), |
| 52 | ], parentid='PARENTKEY') |
| 53 | |
| 54 | # Upload files to existing attachment items |
| 55 | result = zot.upload_attachments(attachment_items, basedir='/path/to/files/') |
| 56 | # Existing entries need editable attachment dicts with key + version; |
| 57 | # filename resolves on disk relative to basedir. Do not set parentid for existing items. |
| 58 | if result['failure']: |
| 59 | raise RuntimeError(result['failure']) |
| 60 | ``` |
| 61 | |
| 62 | Upload result structure: |
| 63 | ```python |
| 64 | { |
| 65 | 'success': [attachment_item1, ...], |
| 66 | 'failure': [attachment_item2, ...], |
| 67 | 'unchanged': [attachment_item3, ...] |
| 68 | } |
| 69 | ``` |
| 70 | |
| 71 | ## Attachment Templates |
| 72 | |
| 73 | ```python |
| 74 | # Get template for a file attachment |
| 75 | template = zot.item_template('attachment', linkmode='imported_file') |
| 76 | # linkmode options: 'imported_file', 'linked_file', 'imported_url', 'linked_url' |
| 77 | |
| 78 | # Available link modes |
| 79 | modes = zot.item_attachment_link_modes() |
| 80 | ``` |
| 81 | |
| 82 | ## Downloading All PDFs from a Collection |
| 83 | |
| 84 | ```python |
| 85 | import os |
| 86 | |
| 87 | collection_key = 'COLKEY' |
| 88 | output_dir = '/path/to/output/' |
| 89 | os.makedirs(output_dir, exist_ok=True) |
| 90 | |
| 91 | items = zot.everything(zot.collection_items_top(collection_key)) |
| 92 | for item in items: |
| 93 | # A top-level item can itself be a standalone attachment. |
| 94 | children = ([item] if item['data']['itemType'] == 'attachment' else |
| 95 | zot.everything(zot.children(item['data']['key']))) |
| 96 | for child in children: |
| 97 | if child['data']['itemType'] == 'attachment' and \ |
| 98 | child['data'].get('contentType') == 'application/pdf' and \ |
| 99 | child['data'].get('linkMode') in {'imported_file', 'imported_url'}: |
| 100 | try: |
| 101 | # Key-based filenames prevent collisions between identically named PDFs. |
| 102 | zot.dump(child['key'], filename=f"{child['key']}.pdf", path=output_dir) |
| 103 | except Exception as e: |
| 104 | print(f"Failed to download {child['data']['key']}: {e}") |
| 105 | ``` |
| 106 | |
| 107 | Upload results are distinct from `create_items()` results: lists under `success`, `failure`, and `unchanged`. Returned successful entries carry the current `version`; creation failures may include an `error` dict. The SDK manages file authorization, upload, and registration through `/items/{key}/file`, including MD5 preconditions and the storage URL returned by Zotero. A completed metadata create alone does not prove the file uploaded. See [official upload protocol](https://www.zotero.org/support/dev/web_api/v3/file_upload). |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

