Request File
Handling user-uploaded files, such as photos and documents, is a common requirement in web applications. The RequestFile
class in Vania simplifies the process of storing these uploaded files.
File Uploads
To store an uploaded file, use the store
method, specifying the desired storage path:
class UserController extends Controller {
Future<Response> updateAvatar(Request request) async {
await request.validate({
'avatar': 'file:jpg,jpeg,png',
}, {
'avatar.file': 'The avatar must be an image file.',
});
if (request.hasFile('file')) {
RequestFile? avatar = request.file('avatar');
String avatarPath = '';
avatarPath = await avatar.store(
path: 'users/${Auth().id()}',
filename: avatar.getClientOriginalName); // The file path will be /storage/app/public/users/user_id/filename.jpg
}
return Response.json({'message': 'User avatar updated successfully'});
}
}
Custom Path
If you need to store a file at a custom path, use the move
method. This is useful for placing files in the public
directory, allowing them to be accessed directly via URL (e.g., https://mydomain.com/users/user_id/file.jpg
):
String path = await avatar.move('public/users/${Auth().id()}', avatar.getClientOriginalName);