1.用element-ui上传图片到nodejs服务器

<el-upload class="upload-container" ref="upload" action="http://localhost:8080/api/upload"
            :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" list-type="picture-card"
            :limit='1' :headers='uploadHeaders' :before-upload="beforeAvatarUpload" :auto-upload="false"
            :on-success='handleSucess' :on-error='handleError'>
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过10M</div>
 </el-upload>

 有些文章推荐使用http-request来定义上传,我试过后发现后台获取不到图片信息,然后使用的action,如果有成功的例子,可以交流下。

< script >
	let self;
export default {

	data() {

		return {
			//上传图片参数
			fileList: [{
				name: 'food.jpeg',
				url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
			}],
		},
		computed: {
				//计算属性
				uploadHeaders() {
					return {
						Authorization: this.$store.state.id_token
					}
				}
			},
			mounted() {
				self = this;
			},
			methods: {
				submitUpload() {
					this.$refs.upload.submit();
				},
				handleRemove(file, fileList) {
					fileList.splice(file, 1);
					console.log(file, fileList);
				},
				handlePreview(file) {
					console.log(file);
				},
				//图片上传前
				beforeAvatarUpload(file) {
					const isJPG = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png');
					const isLt2M = file.size / 1024 / 1024 < 10;
					if (!isJPG || !isLt2M) {
						this.$notify({
							title: "提示",
							message: '只能上传 jpg/jpeg/png文件,且不超过10M',
							type: "warning",
							duration: 3000
						});

					}
					return isJPG && isLt2M;
				},
				//上传成功过后
				handleSucess(response, file, fileList) {
					console.log(response);
					if (response.code == 0) {
						let data = response.data;
						 
						let file = {};
						file.name = data.name;
						file.url = self.$store.state.imgurlhttp + data.url;
						self.fileList[0] = file;
						return;
					} else {
						this.$notify({
							title: "失败",
							message: response.message,
							type: "warning",
							duration: 2000
						});
					}					 
				},
				//上传失败
				handleError(err, file, fileList) {
					console.log(err);
					this.$notify({
						title: "失败",
						message: "上传失败",
						type: "warning",
						duration: 2000
					});
				},

			}

	}
}

</script>

2.nodejs 服务

使用formidable包

npm install formidable 

创建一个system.js文件 ,访问此后台文件上传

const express = require('express');
let router = express.Router();
var formidable = require('formidable');

var path = require("path");
var fs = require("fs");

router.post("/upload", function (req, res) {
    let datas = {};
    datas.code = '0';
    datas.message = '上传图片成功';
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    let PUBLIC_PATH = '../public';
    console.log("PUBLIC_PATH:" + PUBLIC_PATH);
    console.log(__dirname);
    let filedr = "/upload";
    form.uploadDir = path.join(__dirname + filedr);
    form.keepExtensions = true; //保留后缀
    form.maxFieldsSize = 2 * 1024 * 1024;
    //处理图片
    form.parse(req, function (err, fields, files) {
        console.log(files.file);
        var filename = files.file.name
        var nameArray = filename.split('.');
        var type = nameArray[nameArray.length - 1];
        var name = '';
        for (var i = 0; i < nameArray.length - 1; i++) {
            name = name + nameArray[i];
        }
        var date = new Date();
        // var time = '_' + date.getFullYear() + "_" + date.getMonth() + "_" + date.getDay() + "_" + date.getHours() + "_" + date.getMinutes();
        //var avatarName = '/' + name + '_' + date.getTime() + '.' + type;
        var avatarName = '/' + date.getTime() + '.' + type;
        var newPath = form.uploadDir + avatarName;
        fs.renameSync(files.file.path, newPath); //重命名
        // res.send({data:"/upload/"+avatarName})
        let data = {};
        data.name = avatarName;
        data.url = filedr + avatarName;
        datas.data = data
        res.send(datas);
        return;
    })
});

module.exports = router;

3.重后台读取图片app.js

const express = require('express')

//Express框架默认使用body-parser作为请求体解析中间件
const bodyParse = require('body-parser') 
const system = require('./routers/system') 
const fs = require('fs')

const app = express()
//处理跨域
app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Authorization");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();

});
//处理post字段请求
app.use(bodyParse.json());
app.use(bodyParse.urlencoded({
    extended: false
}));
//图片加载,
app.get('/routers/upload/*', function (req, res) {
    let file_path = __dirname + "/" + req.url;

    fs.readFile(file_path, 'binary', function (err, data) {
        if (err) {
            console.log(err);
        } else {
            //console.log(data);
            console.log("输出文件");
            //不加这句,页面可能会乱码,图片包含中文也会乱码
            res.writeHead(200, {
                'Content-Type': 'image/jpeg'
            });
            res.write(data, 'binary');
            res.end();
        }
    })
})

app.use('/api/system', system);
 
app.listen(3012, () => console.log("启动端口号:3012"));

 

 

Logo

前往低代码交流专区

更多推荐