-
-
Notifications
You must be signed in to change notification settings - Fork 235
File Manipulation
You may want to manipulate files before saving them. For example, if a user uploads a large image, you may want to reduce its resolution, crop it, compress it, etc. before allowing the storage adapter to save it. You may also want to convert to another content type or change the filename or encrypt the file. You can do all of this by defining stream transformations on a store.
Note: At the moment transform only work on the server-side code.
The most common type of transformation is a "write" transformation, that is,
a function that changes the data as it is initially stored. You can define
this function using the transformWrite option on any store constructor. If the
transformation requires a companion transformation when the data is later read
out of the store (such as encrypt/decrypt), you can define a transformRead
function as well.
For illustration purposes, here is an example of a transformWrite function that doesn't do anything:
transformWrite: function(fileObj, readStream, writeStream) {
readStream.pipe(writeStream);
}The important thing is that you must pipe the readStream to the writeStream before returning from the function. Generally you will manipulate the stream in some way before piping it.
Sometimes you also need to change a file's metadata before it is saved to a particular store. For example, you might have a transformWrite function that changes the file type, so you need a beforeWrite function that changes the extension and content type to match.
The simplest type of beforeWrite function will return an object with extension, name, or type properties. For example:
beforeWrite: function (fileObj) {
return {
extension: 'jpg',
type: 'image/jpg'
};
}This would change the extension and type for that particular store.
Since beforeWrite is passed the fileObj, you can optionally alter that directly. For example, the following would be the same as the previous example assuming the store name is "jpegs":
beforeWrite: function (fileObj) {
fileObj.extension('jpg', {store: "jpegs", save: false});
fileObj.type('image/jpg', {store: "jpegs", save: false});
}(It's best to provide the save: false option to any of the setters you call in beforeWrite.)
footer25555555