zoukankan      html  css  js  c++  java
  • nodejs关于前后端图片上传的思路及实现代码

    1.前端角度

    a.将图片发给后端 ajax
    1.前端获取图片信息 文件域
    2.将文件信息 存到formdata
    3.调用后端写的api接口发送数据
    b.接受返回的数据
    前端页面显示图片
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
        <title>Document</title>
    </head>
    
    <body>
            <input type="file" id=‘put‘>
            <img src=""  width="500" >
            <button id="btn">上传图片</button>
    </body>
    <script>
        var btn = document.getElementById("btn");
        let npath=‘http://10.9.22.225:5500‘;
        btn.onclick = function(){
          //通过文件域获取上传的图片信息
            var a = document.getElementById("put").files[0];
            console.log(a);
            var formdata = new FormData();
            console.log(formdata);
            formdata.append(‘img‘,a);
            console.log(formdata.get(‘img‘))
          
            $.ajax({
                url:npath+‘/aa‘,
                data:formdata,
                type:‘POST‘,
                processData: false,//必须
                contentType: false,//必须
                success:function(data){
                    //console.log(data)
                    console.log(data)
                    var imgpath=   data.imgPath
                    $(‘img‘).attr(‘src‘,imgpath)
                }
          })
        }
        
        
    </script> 
    </html>

    广州品牌设计公司https://www.houdianzi.com PPT模板下载大全https://redbox.wode007.com

    2.后端角度

    目的:将前端上传的图片
    1.图片本身应该能被访问(静态资源目录)
    a.获取图片上传的数据 (multer().singer(‘hehe‘) req.file)
    b.将数据存到文件里面去 fs.writeFile(‘路径‘,req.file.buffer)
    文件名不重复(时间戳+随机水)
    后缀名和源文件保持一致(minitype)
    上传的文件大小不能超过一定尺寸(size)
    写入路径用绝对路径 path.join(__dirname,‘./www‘)
    2.路径信息存到数据里去
    const express = require(‘express‘)
    let app = express()
    const multer = require(‘multer‘)
    const fs = require(‘fs‘)
    const path = require(‘path‘)
    //single是单图片上传,多图片上传 array ,single里面就是上传图片的key值 
    //和图片相关的是req.file 
    app.use(‘/public‘,express.static(path.join(__dirname,‘./www‘)))
    
    app.post(‘/aa‘,multer().single(‘img‘),(req,res)=>{
        let {buffer,mimetype} = req.file;
        let fileName = (new Date()).getTime() + parseInt(Math.random()*3435) + parseInt(Math.random()*6575);
        let fileType = mimetype.split(‘/‘)[1];
        let filePath =  path.join(__dirname,‘/www/images‘)
        let apath = `http://localhost:5500/public/images/${fileName}.${fileType}`
       
        fs.writeFile(`./www/images/${fileName}.${fileType}`,buffer,(data)=>{
            if(data){
                res.send({err:0,msg:"上传失败"})
            }else{
                res.send({err:1,msg:"上传成功",imgPath:apath})
            }
        })
    })
    
    app.listen(‘5500‘,()=>{
        console.log(‘start‘)
    })

    3.注意事项

    1.数据类型 formdata
    2.方法 post
    3.正常ajaxpost的数据格式 表单 json
  • 相关阅读:
    git执行sudo git pull origin xxx 提示 AutoMatic merge failed;fix conflicts and then commit the result
    mysql 两表关联更新
    宝塔上的redis 性能调整的requirepass 密码与配置文件的 requirepass 不一致
    php 默认文档为index.htm 或者其他
    layerui 弹窗里出现下拉框select
    微信小程序文字超出显示省略号
    MySQL用存储过程创建日期字典表
    书单
    手动更新表记录时自动更新 UPDATE_DATE
    Nginx $proxy_add_x_forwarded_for 实现多租户判断
  • 原文地址:https://www.cnblogs.com/qianxiaox/p/14102641.html
Copyright © 2011-2022 走看看