node express formidable 檔案上傳後修改檔案名稱

來源:互聯網
上載者:User

標籤:inpu   檔案   user   失敗   put   username   submit   min   rmi   

//我是用php的思想來學習nodejs

var express = require(‘express‘);var router = express.Router();var fs = require(‘fs‘);var path= require("path");var formidable = require(‘formidable‘);/* GET home page. */router.get(‘/‘, function(req, res, next) { res.render(‘index‘, { title: ‘Express+EJS+mysql+s2‘ });});router.post(‘/file-upload‘, function(req, res, next) { console.log(‘開始檔案上傳....‘); var form = new formidable.IncomingForm(); //設定編輯 form.encoding = ‘utf-8‘; //設定檔案儲存體路徑 form.uploadDir = "./public/images/"; //保留尾碼 form.keepExtensions = true; //設定單檔案大小限制 form.maxFieldsSize = 2 * 1024 * 1024; //form.maxFields = 1000; 設定所以檔案的大小總和 form.parse(req, function(err, fields, files) { //console.log(fields); console.log(files.thumbnail.path); console.log(‘檔案名稱:‘+files.thumbnail.name); var t = (new Date()).getTime(); //產生隨機數 var ran = parseInt(Math.random() * 8999 +10000); //拿到副檔名 var extname = path.extname(files.thumbnail.name); //path.normalize(‘./path//upload/data/../file/./123.jpg‘); 標準格式檔案名稱 var oldpath = path.normalize(files.thumbnail.path); //新的路徑 let newfilename=t+ran+extname; var newpath = ‘./public/images/‘+newfilename; console.warn(‘oldpath:‘+oldpath+‘ newpath:‘+newpath); fs.rename(oldpath,newpath,function(err){ if(err){ console.error("改名失敗"+err); } res.render(‘index‘, { title: ‘檔案上傳成功:‘, imginfo: newfilename }); }); //res.end(util.inspect({fields: fields, files: files})); }); });/* supervisor ./bin/www */module.exports = router;
<!DOCTYPE html><html><head><title><%= title %></title><link rel=’stylesheet’ href=’/stylesheets/style.css’ /></head><body><h5>這裡變數沒有輸出但沒有報銷:<%= locals.title %></h5><p>Welcome to <%= title %></p><img src=‘./images/<%= locals.imginfo %>‘ width=‘200‘/><form method="post" enctype="multipart/form-data" action="/file-upload">  <input type="text" name="username">  <input type="password" name="password">  <input type="file" name="thumbnail">  <input type="submit"></form></body></html>

 

node express formidable 檔案上傳後修改檔案名稱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.