NodeJs actual combat-Express builds a photo storage website (3)-download pictures

NodeJs actual combat-Express build photo storage website 3-download pictures

Add a download link to the page

  1. Modify the index.ejs view file to add the link label a
<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <a href="/photo/upload">点击上传</a>
    <p>照片存储应用</p>
    <div id="photos">
        <% data.forEach(item => {
    
     %>
            <div class="photo">
                <h2><%=item.name%></h2>
                <a href="/photo/download?fileName=<%=item.file_name%>">
                  <img src='<%=item.path%>'/>
                </a>
            </div>
        <%})%>
    </div>
  </body>
</html>

When the a tag is clicked, the browser will request the /photo/download interface

Add the route corresponding to the download

Modify photo.js to add download route

router.get('/download', function (req, res, next) {
    
    
  var filePath = destpath + req.query.fileName;
  if (fs.existsSync(filePath)) {
    
    
    var absPath = path.resolve(filePath);
    res.download(absPath);
  } else {
    
    
    res.send('文件不存在');
  }
});
  1. First determine whether the file exists
  2. If the file exists, get the absolute path of the file
  3. output file to browser

Thinking: If you change res.download(absPath); to res.sendFile(absPath);, can you still download the file?

  1. complete photo.js
var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var path = require('path');
var fs = require('fs');
var silly = require('silly-datetime');
var destpath = "./public/images/";
var urlpath = "/images/";


/* GET photo page. */
router.get('/', function (req, res, next) {
    
    
    let arr = fs.readdir(destpath, function(err, files) {
    
    
      if (err) {
    
    
        console.log('读取文件夹错误:', err);
      } else {
    
    
        var photos = [];
        files.forEach(fileName => {
    
    
          let item = {
    
    
            'name':'',
            'path':'',
            'file_name':''
          };
          item.name = findFileName(fileName);
          item.path = urlpath + fileName;
          item.file_name = fileName;
          photos.push(item);
        });
        res.render('photos', {
    
     title: 'Photos', data: photos });
      }
    });
});

router.get('/upload', function (req, res, next) {
    
    
  res.render('photos/upload', {
    
     title: '图片上传' });
});

router.post('/submit', function (req, res, next) {
    
    
  var form = new multiparty.Form();
  form.encoding = 'utf-8';
  form.uploadDir = destpath;
  form.maxFilesSize = 20 * 1024 * 1024;
  form.parse(req, (err, fields, files) => {
    
    
    if (err) {
    
    
      console.log('解析上传文件错误:', err);
    } else {
    
    
      var originalFilename = files.file[0].originalFilename;
      var fileType = findFileType(originalFilename);
      var fileName = originalFilename;
      if (fields.name != null) {
    
    
        fileName = fields.name[0] + fileType;
      }
      var uploadedPath = files.file[0].path;
      var newFileName = destpath + formatDate(new Date()) + "_" + fileName;
      fs.rename(uploadedPath, newFileName, (err) => {
    
    
        if (err) {
    
    
          console.log('重命名文件错误:', err);
        }
        res.redirect('/photo');
      });
    }
  });

});

router.get('/download', function (req, res, next) {
    
    
  var filePath = destpath + req.query.fileName;
  if (fs.existsSync(filePath)) {
    
    
    var absPath = path.resolve(filePath);
    res.download(absPath);
  } else {
    
    
    res.send('文件不存在');
  }
});

function findFileType(originalFilename) {
    
    
  var lastIndex = originalFilename.lastIndexOf('.');
  if (lastIndex != -1) {
    
    
    return originalFilename.substring(lastIndex);
  }
  return originalFilename;
}

function findFileName(inputFileName) {
    
    
  var lastIndex = inputFileName.lastIndexOf('.');
  if (lastIndex != -1) {
    
    
    return inputFileName.substring(0, lastIndex);
  }
  return inputFileName;
}

function formatDate(date) {
    
    
  if (date == null) {
    
    
    return "";
  }
  return silly.format(date, 'YYYYMMDD-HHmmss');
}

module.exports = router;

renderings

After starting the service, click on the picture to download the output picture
insert image description here

project address

https://gitee.com/3281328128/photo/tree/master/

Guess you like

Origin blog.csdn.net/modelmd/article/details/128045014