【问题标题】:How to upload a file?如何上传文件?
【发布时间】:2021-12-06 18:52:29
【问题描述】:

我一直在尝试使用 adonisjs 上传一个简单的图像,并且 request.file() 一直返回 null。

我对 adonisjs 还是很陌生,文档并不清楚该怎么做。

我正在使用 SQLite 数据库。

这是我的控制器。

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}`)

}

这是我用来提交图片的表单。

<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>

这是我正在使用的路线

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

【问题讨论】:

    标签: html sqlite adonis.js


    【解决方案1】:

    AdonisJS 为您提供强大且高性能的 API 来处理文件上传。您不仅可以在本地处理和存储上传的文件,还可以将它们直接流式传输到 S3、Cloudinary 或 Google 云存储等云服务。

    访问上传的文件

    在 start/kernel.ts 文件中注册的 bodyparser 中间件会自动处理 multipart/form-data 请求的所有文件。

    您可以使用 request.file 方法访问文件。该方法接受字段名称并返回 File 类的实例,如果没有上传文件,则返回 null。

    试试这个代码

    <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>
    

    控制器

    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
          })
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-24
      • 2011-11-11
      • 2016-08-07
      • 2018-01-09
      • 2014-05-18
      • 2015-02-20
      • 2016-08-23
      相关资源
      最近更新 更多