Node. js development tutorial-object upload and Verification Based on the OnceIO framework

Source: Internet
Author: User
This article mainly introduces Node. the js development tutorial is based on the OnceIO framework for file upload and verification. It is very good and has reference value. If you need it, you can refer to OnceIO as an OnceDoc Enterprise Content (online disk) the underlying Web framework, which can realize full cache of template files and static files. It does not require I/O operations and supports Client Cache Optimization, GZIP compression and so on (only for the first compression), with excellent performance, saving you server costs. Its modular function enables distributed storage of your Web, that is, an extended package contains frontend, backend, and database definitions, you only need to add/delete directories to delete functions and implement modular extension. Here is a series of articles about how to use OnceIO.

In this section, we will demonstrate how to use OnceIO to upload files.

Create a form in a webpage File

Take a simple webpage file.html with only the file upload function as an example:

 

The browser displays the following results:

Create server Receiving File Logic

The websvr. js code of the Server File is as follows:

var fs = require('fs')var path = require('path')var onceio = require('../onceio/onceio')var app = onceio()app.get('/', function(req, res){res.render('file.html')})app.file('/file/upload', function(req, res) {var fileInfo = req.files.file || {}fs.link(fileInfo.path, path.join('./fileStore', fileInfo.name))res.send('File Uploaded Successfully')}).before(function(req, res) {var contentLength = req.headers['content-length'] || 0if (contentLength > 1048576) {res.send({ error: 'Error: File Size Limit (1 MB) Exceeded' })} else {return true}})

Var fs = require ('fs') and var path = require ('path') respectively import Node. the file system (fs) module for file operations provided by js and the path module for processing file paths.

App. file (path, callback ). before (callback) is equivalent to app. use (path, callback, {file: true }). before (callback) is a middleware for processing uploaded files.

After a file is uploaded, its size, storage address, name, format, and modification time are stored in req. in the file attribute of files (the value of name in the input tag with type 'file'), its size information will be placed in req. in the content-length attribute of headers.

Before Function

Before is one of the main differences between OnceIO and other Web frameworks. It can perform some basic verification on the file before receiving the file, such as the size and type, in order to obtain the best performance. Return true indicates that the file is verified and received. Otherwise, the connection is closed and the upload is canceled. In before, the req. session object is unavailable because the session may exist in a file or in redis. It takes time to obtain the session. The before function must immediately determine the validity of the file.

In this example, the before callback function is based on req. content-length in headers determines whether the size of the uploaded file has exceeded the size limit (the developer can change the size limit of the File Upload by modifying the constant in the if statement. The unit of content-length is byte, 1024*1024 indicates 1 MB). If the value exceeds the limit, the file will not be uploaded and the server will return an error message. If the value does not exceed the limit, the server will continue to execute the app. the callback function in file transfers the file from the temporary address to the specified storage address, and the file is uploaded here.

Solve the Problem of file name duplication

Our current server program cannot solve the problem of file name duplication. If the user uploads a file with the same name, the server will return an error that already exists in the file. To solve this problem, we can add a timestamp between the file's main file name and extension name. The function code for this processing is as follows:

var timestampName = function(fileName){// get filename extensionvar extName = path.extname(fileName)// get base name of the filevar baseName = path.basename(fileName, extName)// insert timestamp between base name and filename extension// the plus sign ('+') before new Date() converts it into a numberreturn baseName + +new Date() + extName}

Replace fileInfo. name in the fs. link statement with timestampName (fileInfo. name ):

fs.link(fileInfo.path, path.join('./fileStore', timestampName(fileInfo.name)))

The improved server program allows users to upload duplicate files. The preceding five files named 'cache_workflow.png 'are uploaded as an example, five files with names starting with 'cache _ workflow' but with different timestamps will appear in the server's file storage address:

For more information about how to upload and verify files based on the OnceIO framework, see PHP!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.