


How nodejs uses http module to write upload image interface test client
This time I will show you how nodejs uses the http module to write the upload image interface test client. Nodejs uses the http module to write the upload image interface test client. What are the precautions?The following is a practical case, one Get up and take a look.
Build a simple upload test server
For example: write a simple server with python flask
from flask import Flask, url_for, request,redirect,send_from_directoryimport os app = Flask(name) app.config['UPLOAD_FOLDER'] = 'uploads/' # 保存文件位置ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])@app.route('/uploads/<filename>')def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename)@app.route('/', methods=['GET', 'POST'])def upload_file(): if request.method == 'POST': file = request.files['file'] if file : file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) return redirect(url_for('uploaded_file', filename=file.filename)) return ''' <html><head><title>上传测试</title> </head><body><h1>上传测试</h1> <script> function upl(){ var form = new FormData(); form.append("file", document.getElementsByName("file")[0].files[0]); var oReq = new XMLHttpRequest(); oReq.open("POST", "/"); oReq.send(form); } </script> <form action="" method="post" enctype="multipart/form-data"> <p><input type="file" name="file"> <input type="submit" value="表单提交"> </p></form> <input type="button" value="ajax提交" onclick="upl()"> </body> </html> '''with app.test_request_context(): # 输出url passif name == 'main': # app.debug = True app.run()
2. Observe the upload header identifier
After running the server Open the browser to access, open the console at the address, upload any file, and observe
3.nodejs writing upload test client
var http = require('http');var querystring = require('querystring');var fs = require('fs');var post_data = { };//post提交数据var content = querystring.stringify(post_data);#将对象转换成字符串,字符串里多个参数将用 ‘&' 分隔,将用 ‘=' 赋值var boundaryKey = new Date().getTime();//创建随机切割标识字 你可以百度 'multipart form-data boundary'了解//var boundaryKey =Math.random().toString(16); var options = { hostname: '127.0.0.1', port: 5000, path: '/', method: 'POST', headers: { // 'Accept': '*/*', // 'Accept-Encoding': 'gzip, deflate', // 'Connection': 'keep-alive', 'Content-Type':'multipart/form-data; boundary=----'+boundaryKey,//文件上传标识与切割标识 // 'Host':'127.0.0.1:5000', // 'Origin':'http://127.0.0.1:5000', // 'Referer':'http://127.0.0.1:5000/', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36' } };var req = http.request(options, function (res) { res.setEncoding('utf8'); console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); res.on('end', function () { console.log('res end'); }); });var payload ='\r\n------'+boundaryKey+'\r\n' + 'Content-Disposition: form-data; name="file"; filename="test.png"\r\n' + 'Content-Type: image/png\r\n\r\n';var enddata = '\r\n------'+boundaryKey+'--'; req.setHeader('Content-Length', Buffer.byteLength(payload) + Buffer.byteLength(enddata) + fs.statSync("./test.png").size); req.write(payload);var fileStream = fs.createReadStream("./test.png", { bufferSize: 4 * 1024 }); fileStream.pipe(req, { end: false }); fileStream.on('end', function () { req.end(enddata); }); req.on('error', function (e) { console.log('problem with request: ' + e.message); }); req.write(content);// req.end();
There is another way to write:
var http = require('http');var querystring = require('querystring');var fs = require('fs');var boundaryKey = new Date().getTime()//Math.random().toString(16); //创建随机切割标识字var options = { hostname: '127.0.0.1', port: 5000, path: '/', method: 'POST', headers: { // 'Accept': '*/*', // 'Accept-Encoding': 'gzip, deflate', // 'Connection': 'keep-alive', 'Content-Type': 'multipart/form-data; boundary=----' + boundaryKey, // 'Host':'127.0.0.1:5000', // 'Origin':'http://127.0.0.1:5000', // 'Referer':'http://127.0.0.1:5000/', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36' } };var req = http.request(options, function (res) { res.setEncoding('utf8'); console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); res.on('end', function () { console.log('res end'); }); });var payload = '\r\n------' + boundaryKey + '\r\n' + 'Content-Disposition: form-data; name="file"; filename="test.png"\r\n' + 'Content-Type: image/png\r\n\r\n';var enddata = '\r\n------' + boundaryKey + '--';var fileStream=fs.readFileSync("./test.png"); req.setHeader('Content-Length', Buffer.byteLength(payload) + Buffer.byteLength(enddata) + fs.statSync("./test.png").size);console.log(payload); req.write(payload);console.log(fileStream); req.write(fileStream);console.log(enddata); req.end(enddata); req.on('error', function (e) { console.log('problem with request: ' + e.message); });
believe it After reading the case in this article, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Related reading:
h5 production of performance change line chart
##Detailed explanation of the separation of front-end and back-end development of Golang+Nodejs
The above is the detailed content of How nodejs uses http module to write upload image interface test client. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application
