文件上传

文件上传有三种方式:

1,from表单上传,简单方便。

2,Ajax请求上传,异步上传,局部刷新。

3,layui文件上传,步骤麻烦,不推荐。

1,from表单上传:

<form action="/uploadHead" method="POST" enctype="multipart/form-data" class="layui-form">
        <!-- accept="image/*" 指规定文件只能选择图片类型的文件 -->
        <input type="file" name="headImg" accept="image/*" >
        <button>上传头像</button>
</form>

enctype设置表单提交的数据类型,  multipart/form-data指文件类型

2,使用Ajax请求

layui.use(["form", "jquery", "layer"], function(){
            var form = layui.form;
            var $ = layui.jquery;
            var layer = layui.layer;
      console.log($("input")[0].files)
            // 找到input选中的头像文件
      
      var file = $("input")[0].files[0]
            // 把需要上传的文件加入formData对象中(因为ajax上传的是formData对象)
            var formData = new FormData() 
      注意: 第一个参数是input的name值,和后端存储参数对应,等二个参数是文件
      formData.append("headImg", file);       
          // formData.append("username", sessionStorage.getItem("name"))
      //发起ajax请求, 上传头像
                $.ajax({
                    type: "post",
                    url: "/uploadHead",
                    data: formData,
                    // contentType指上传数据类型, jQuey封装ajax时会自动把data对象转成字符串类型, false表示禁止自动转换类型, 因为文件不能转类型
                    contentType: false,
                    // processData指jQuery内部对data数据的加工处理(编码),false可防止文件被加工处理, 保持原有结构
                    processData: false,
                    success: function(){
                        layer.msg("头像已上传",{icon: 1})
         
          // window.parent.document.getElementById("headImg").src = "./HeadImg/张三.jpg"
                  // 这一句无效的原因: img标签设置src地址时,如果src值不变的情况下, img会直接调用缓存, 不会更新 (浏览器自动缓存造成的结果)
                  // 解决方案: 我们在src图片路径后使用?拼接随机数,使设置前后的src不一致, img就会重载图片 (?后的数据叫hash值,不影响路径使用)
          
          window.parent.document.getElementById("headImg").src =
          "./HeadImg/"+ sessionStorage.getItem("name") +".jpg?" + Math.random()
 
  }
                })
           return false; 取消表单的默认提交
  })
        })
 
    console.log(window)  // 当前页HeadImg.html
        console.log(window.parent)  // 外层主页index.html
        console.log(window.document) // 当前页文档对象HeadImg.html
        console.log(window.parent.document)  // 外层主页文档对象index.html
 
 
后端接收文件
var cookieParser = require("cookie-parser")
app.use(cookieParser())
 
var multer = require("multer") // 引入硬盘存储模块
设置磁盘存储配置选项(存储位置和文件名)
var myStorage = multer.diskStorage({
  //设置文件存储位置
  //两个参数
  通过调用callback设置文件存储目录, 参数1是错误信息, 参数2是目录
  destination:function(req, file, callback){
  callback(null,"./public/HeadImg")
}
 
  //设置文件名
  filename:function(req, file, callback){
  // cookie会随ajax请求,被携带在请求头中, 但请求头不支持汉字,会乱码, 所以在本地cookie中存数据时, 汉字要进行url编码,
    // 使用cookie-parser模块可以直接解析请求头中的cookie字符串, 自动解码并生成对象存入req.cookies字段中

    console.log(1, req.headers.cookie, req.cookies)
    callback(null, req.cookies.username + ".jpg")
}
})
 
// 创建硬盘存储对象
var save = multer({
  storage: myStorage
})
// 头像上传接口, 第二个参数用于存储头像, single()表示单文存储 headImg对应input输入框的name
app.post("/uploadHead", save.single("headImg"), function(req, res){
  console.log(2, req.body)
  // 文件上传的回调执行时, 文件就已经存储到磁盘了, 直接响应即可
  res.json({code: 1, msg: "头像已上传"})
})
 
 
 
posted @ 2022-03-25 20:31  俺是前端小菜  阅读(270)  评论(0编辑  收藏  举报