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

转载于:https://www.cnblogs.com/zhouyingying/p/11330484.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值