Home  >  Article  >  Web Front-end  >  Detailed explanation of how to implement simple image upload code in node.js

Detailed explanation of how to implement simple image upload code in node.js

伊谢尔伦
伊谢尔伦Original
2017-07-24 13:09:251355browse

1.node-formidable

Component that helps with file upload

2.app.js


var formidable = require('formidable');
var http = require( 'http' );
var sys = require('sys');
 
http.createServer(function( request ,response ){
  if( request.url == '/upload' && request.method.toLowerCase() == 'post' )
  {
    console.log( 'upload requet ' )
    uploadRequest(request,response);
    return;
  }
  enterRequest(request,response)
}).listen(3000);
 
function enterRequest( request, response )
{
  response.writeHead( 200, { 'Content-type' : 'text/html' });
  response.end(
    &#39;<form action = "/upload" enctype="multipart/form-data" method="post" >&#39; +
    &#39;<input type = "text" name = "title" /> <br>&#39; +
    &#39;<input type = "file" name="upload" multiple="multiple"/> <br/>&#39;+
    &#39;<input type="submit" value="Upload Now"/>&#39; +
    &#39;</form>&#39;
  );
}
 
/**
 * 处理上传的逻辑
 * @param request
 * @param response
 */
function uploadRequest( request,response )
{
  var form = new formidable.IncomingForm();
  form.parse( request, function ( err, fields, files ) {
    response.writeHead(200, {&#39;Content-type&#39; : &#39;text/plain&#39;});
    response.write(&#39;reviced upload file&#39;);
    response.end( sys.inspect(
      {
        fields : fields,
        files : files
      }) );
  });
}

The above is the detailed content of Detailed explanation of how to implement simple image upload code in node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn