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="" alt="" 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>
    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
  • 相关阅读:
    centos rm -rf 恢复删除的文件
    默认hosts后面为files dns
    linux shell expr 使用
    QQ,MSN,Skype在线客服代码
    LocalResizeIMG前端HTML5本地压缩图片上传,兼容移动设备IOS,android
    php读取和保存base64编码的图片内容
    linux shell 字符串操作(长度,查找,替换)详解
    tomcat的简单配置与适用默认的web应用
    mybatis左连接需要输出左表的指定内容与筛选
    first head in html 笔记
  • 原文地址:https://www.cnblogs.com/zhouyingying/p/11330484.html
Copyright © 2011-2022 走看看