我已经使用过 Active Storage 和 Direct Uploads。我已经安装了 ActiveStorage 并创建了数据库,所以添加图像没有问题。我已将此添加到我的模型中:
class Project < ApplicationRecord
has_many_attached :images
end
并将表单字段放在视图中:
<%= f.file_field :images, accept:'image/*', class: "input-file" multiple %>
并将其添加到我的控制器中:
private
def project_params
params.require(:project).permit(:title, :content, images: [])
end
不确定这是否会节省我的数据(因为大多数照片可能会很大),但任何关于实施的建议都会很棒。我想使用base64获得类似canvas compress的东西(再次不确定这是否是最好的)并调整大小,转换为blob然后上传或像compress.js这样的javascript压缩(https://www.npmjs.com/package/compress .js)处理图像,以便在将它们发送到服务器之前在用户端进行压缩和调整大小,从而减少发送的数据量。
我在这里找到了这段代码,我不太确定或者如何集成这样的东西,因为 Javascript 不在我的驾驶室中。
function compressImage (base64) {
const canvas = document.createElement('canvas')
const img = document.createElement('img')
return new Promise((resolve, reject) => {
img.onload = function () {
let width = img.width
let height = img.height
const maxHeight = 200
const maxWidth = 200
if (width > height) {
if (width > maxWidth) {
height = Math.round((height *= maxWidth / width))
width = maxWidth
}
} else {
if (height > maxHeight) {
width = Math.round((width *= maxHeight / height))
height = maxHeight
}
}
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, width, height)
resolve(canvas.toDataURL('image/jpeg', 0.7))
}
img.onerror = function (err) {
reject(err)
}
img.src = base64
})
}
基本上我问的是一个两部分的问题。如果我的用户将上传许多照片(显示分辨率不必保持超高)将使用带有 base64 的画布压缩然后将图像作为 blob 返回是最好的用途,或者只是坚持直接上传(rails js)而不是为压缩图像而烦恼?第二部分是如果这是一个好主意,我将如何实施?许多网站已经在不需要保持原始照片大小的情况下这样做了。