主要使用fs模块的pipe方法,简单粗暴:
import fs from "fs"; import path from 'path'; import request from 'request'; const movieDir = "./"; const movieName = "download_movie"; const url = "http://img4.imgtn.bdimg.com/it/u=2389140428,1315216178&fm=23&gp=0.jpg"; request.get(url).pipe(fs.createWriteStream(path.join(movieDir, movieName + '.jpg')));
输出一张图片:
var http = require("http"); var fs = require("fs"); http.createServer(function(req, res) { fs.createReadStream("./20170313185619.png").pipe(res); }).listen(3000, "127.0.0.1");
上传图片:
var express = require('express') var multer = require('multer') var app = express() var storage = multer.diskStorage({ //设置上传后文件路径,uploads文件夹会自动创建。 destination: function(req, file, cb) { cb(null, './uploads') }, //给上传文件重命名,获取添加后缀名 filename: function(req, file, cb) { var fileFormat = (file.originalname).split("."); cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]); } }); //添加配置文件到muler对象。 var upload = multer({ storage: storage }); app.post('/profile', upload.single('avatar'), function(req, res, next) { // req.file 是 `avatar` 文件的信息 res.send("upload success") }); app.listen(3000);