Skip to content

Commit

Permalink
[client] Add docs for asset uploads
Browse files Browse the repository at this point in the history
  • Loading branch information
bjoerge committed Sep 27, 2017
1 parent 69b7d2e commit a6a22a1
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions packages/@sanity/client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,87 @@ client.mutate(transaction)

An important note on this approach is that you cannot call `commit()` on transactions or patches instantiated this way, instead you have to pass them to `client.mutate()`

### Uploading assets

Assets can be uploaded using the `client.assets.upload(...)` method.

```
client.asset.upload(type: 'file' | image', body: File | Blob | NodeStream): Promise<AssetDocument>
```

Read more about [assets in Sanity](https://sanity.io/docs/http-api/assets)

#### Examples: Uploading assets from Node.js
```js
// Upload a file from the file system
client.assets.upload('file', fs.createReadStream('myFile.txt'))
.then(document => {
console.log('The file was uploaded!', document)
})
.catch(error => {
console.error('Upload failed:', error.message)
})
````
```js
// Upload an image file from the file system
client.assets.upload('image', fs.createReadStream('myImage.jpg'))
.then(document => {
console.log('The image was uploaded!', document)
})
.catch(error => {
console.error('Upload failed:', error.message)
})
```

#### Examples: Uploading assets from the Browser
```js
// Create a file with "foo" as its content
const file = new File(["foo"], "foo.txt", {type: "text/plain"})
// Upload it
client.assets.upload('file', file)
.then(document => {
console.log('The file was uploaded!', document)
})
.catch(error => {
console.error('Upload failed:', error.message)
})
````
```js
// Draw something on a canvas and upload as image
const canvas = document.getElementById('someCanvas')
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#f85040'
ctx.fillRect(0, 0, 50, 50);
ctx.fillStyle = '#fff'
ctx.font = '10px monospace'
ctx.fillText('Sanity', 8, 30)
canvas.toBlob(uploadImageBlob, 'image/png')

function uploadImageBlob(blob) {
client.assets.upload('image', blob, "image/png")
.then(document => {
console.log('The image was uploaded!', document)
})
.catch(error => {
console.error('Upload failed:', error.message)
})
}
```
### Deleting an asset

```
client.assets.delete(type: 'image' | 'file', id: string): Promise
```

```js
client.assets.delete('image', '1a2b3c')
.then(result => {
console.log('deleted imageAsset', result)
})
```

### Get client configuration

```js
Expand Down

0 comments on commit a6a22a1

Please sign in to comment.