How to upload a file?

Viewed 283

I have been trying to upload a simple image using adonisjs and the request.file() keeps on returning null.

I am pretty new to adonisjs and the documentation is not clear on what to do.

I am using a SQLite database.

This is my controller.

public async update({response, request}) {
    let user = request.only(["userId","fullname","avatar"]);
    const coverImage = request.file('avatar')
    console.log(coverImage)
    console.log(user)

    if (!coverImage) {
        return "Please upload File"
    }

    const imageName = new Date().getTime().toString()+ '.' + coverImage.subtype 
    await coverImage.moveAll(Application.publicPath('images'),{
            name: imageName
        })
    
    user.avatar = `images/${imageName}`
    await user.save()

    return response.redirect(`/users/${user.userId}`)

}

This is my form that I am submitting the image with.

<form class="uk-grid-small" uk-grid method="post" action="{{ route('profiles.update', {id: user.id}) }}?_method=PUT">
        <div class="uk-width-1-2@s">
            <input class="uk-input" type="text" placeholder="Fullname" name="fullname">
        </div>
        <div class="uk-width-3-4@s">
            <label>Upload user avatar</label> 
            <input type="file" multiple name="avatar" class="form-control">
        </div>
        <div class="uk-width-1-2@s">
            <button class="uk-button uk-button-primary">Submit</button>
        </div>
    </form>

This is the route I am using

Route.resource('profiles', 'ProfilesController')
1 Answers

AdonisJS provides you a robust and performant API for dealing with file uploads. Not only can you process and store uploaded files locally, but you can also stream them directly to the cloud services like S3, Cloudinary, or Google cloud storage.

Accessing uploaded files

The bodyparser middleware registered inside the start/kernel.ts file automatically processes all the files for multipart/form-data requests.

You can access the files using the request.file method. The method accepts the field name and returns an instance of the File class, or null if no file was uploaded.

try this code

<form action="{{ route('posts.store') }}" method="POST" enctype="multipart/form-data">
      <div class="row">
        <div class="col">
          <div class="custom-file">
            <input type="file" class="custom-file-input" name="image_url" id="validatedCustomFile" required>
            <label class="custom-file-label" for="validatedCustomFile">Choose file...</label>
            <div class="invalid-feedback">Example invalid custom file feedback</div>
          </div>
        </div>
      </div>
      
      <button type="submit" class="btn btn-success mt-2">Submit</button>
    </form>

controller

const postImage = request.file('image_url', {
      size: '2mb',
      extnames: ['jpg', 'png'],
    })
    let date_ob = new Date();
    if (!postImage) {
      return
    }
    if (!postImage.isValid) {
      return postImage.errors
    }
    if (postImage) {
      await postImage.move(Application.publicPath('postImage'), {
        name: ("0" + date_ob.getDate()).slice(-2)+("0" + (date_ob.getMonth() + 1)).slice(-2)+date_ob.getFullYear()+date_ob.getHours()+date_ob.getMinutes()+date_ob.getSeconds()+date_ob.getMilliseconds()+'.'+postImage.extname,
        overwrite: true, // overwrite in case of conflict
      })
    }
Related