我有一个输入,用户可以上传图像,我想获取该图像并将其传递到服务器端,服务器会将该图像存储在本地文件夹中,例如:

我使用Linux作为服务器,因此server.js从文件夹/home/user/project/server/server.js运行.当服务器获得我希望它存储在文件夹/home/user/project/Images/img.jpg上的图像时

这是我的密码:

Html:

<input type="file" id="imageFile" accept=".jpg, .jpeg, .png" />

前端:

const signup = async () => {
  const name = document.getElementById("signup_name").value;
  const passwd = document.getElementById("signup_passwd").value;
  const image = document.getElementById("imageFile").files[0];
  let formData = new FormData();
  formData.append("fileToUpload", image);
  const response = await fetch("http:/localhost:3000/signup", {
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      nome: cadastro_nome,
      senha: cadastro_senha,
      imagem: formData
    }),
  });
  const result = await response.json();
  document.getElementById("cadastro_nome").value = "";
  document.getElementById("cadastro_senha").value = "";
  alert(result);
};

后端:

app.post("/signup", async (req, res) => {
  const { name, passwd, image } = req.body;
  if (!name || !passwd) {
    return res.status(400).json("Dados incorretos!");
  }
  knex
    .transaction((trx) => {
      trx
        .insert({
          login: name,
          senha: passwd,
          divida: 0,
        })
        .into("usuarios")
        .then(trx.commit)
        .catch(trx.rollback)
        .then(res.json("Cadastrado com sucesso!"));
    })
    .catch((err) => {
      console.log(err);
      return res.json("Login existente, tente novamente!");
    });
  //PUT SOMETHING HERE TO SAVE IMAGE LOCALLY, MAYBE??
});

推荐答案

是的,您可以首先使用FileReader将上传的图像存储为Base64字符串,数据URL已经是Base64,因此当您调用Reader.readAsDataURL时,e.Target.Result将发送到Reader.onLoad处理程序,它将是您需要的全部内容,但也可能需要添加到您的HDD中或使用res.json异步执行,判断WDN official documentation约为FileReader.

(Get user's uploaded image for example)

const imgPath = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();

reader.addEventListener("load", function () {
    // Convert file to base64 string and save to localStorage
    localStorage.setItem("image", reader.result);
}, false);

if (imgPath) {
    reader.readAsDataURL(imgPath);
}

要从本地存储读回图像,只需使用querySelector或getElementByID:

const img = document.getElementById('image');
img.src = localStorage.getItem('image');

关于"fd"参数必须是NUMBER类型的,在我的例子中,有时我使用:

  • Fs.readSync(),而我应该使用fs.readFileSync()
  • Fs.WriteSync()使用率,但应为fs.writeFileSync()
  • 在您的情况下,fr.write()可能是fs.writeFile()

我注意到,你问题中@Dimava的 comments 也可以用. 如需更多帮助,请向您的类似问题咨询此post related!;)

Javascript相关问答推荐

如何从JSON数组添加Google Maps标记—或者如何为数组添加参数到标记构造器

通过嵌套模型对象进行Mongoose搜索

InDesign—创建一个独立的窗口,在文档中进行更正时保持打开状态

我可以从React中的出口从主布局调用一个处理程序函数吗?

在网页上添加谷歌亵渎词

可更改语言的搜索栏

如何在coCos2d-x中更正此错误

JavaScript是否有多个`unfined`?

让chart.js饼图中的一个切片变厚?

如何使本地html页面在重新加载时保持当前可隐藏部分的打开状态?

有没有办法通过使用不同数组中的值进行排序

与在编剧中具有动态价值的定位器交互

select 2-删除js插入的项目将其保留为选项

连续添加promise 时,如何在所有promise 都已结算时解除加载覆盖

对不同目录中的Angular material 表列进行排序

更新文本区域行号

使用python,我如何判断一个html复选框是否被隐藏,以及它是否被S选中?

调试jQuery代码以获取所有行的总和(票证类型)

制表机表宽度在第一次加载时缩小,拖动后正在调整

如何在通过JavaScript添加图像后将其删除?