The reason

The development project is egg.js + Redis + mysql + vue2.x family bucket full stack development project. Due to the need to upload files, the file directory structure needs to be generated for the file after uploading successfully, and then the file needs to be compressed for processing. Besides, the file is too large, so the upload speed will be very slow. It’s also complicated to deal with. So he got lazy and left it to us backstage. The Python process is definitely much better, but it also needs to be rewrapped. The original idea was for the front-end to directly call the background, but the manager asked to encapsulate a layer. There was no alternative but to call the interface of the background in Node, that is, the front-end uploads files to the node layer. Node receives files and then simulates the Formdata upload to send files to the python background. So you start coding, and the question is how does Node simulate form uploads?

I searched online for a long time, and all the parameters were spliced together. Well, I was afraid of such complicated things. Later, I searched NPM plug-in and found a form-data plug-in. When using background anyway also can’t receive files Then came up with a kick-ass plugin [superagent] [www.npmjs.com/package/sup]… www.jianshu.com/p/1432e0f29… Vue + AXIos + elementui upload (vue+axios + elementui upload

Eggjs Is configured using eggJS

config.multipart = { mode: “Stream”, fileSize: “1024mb” };

For more information about Stream, you can find many relevant articles on Baidu.

'use strict';
 
const Service = require('egg').Service;
const path = require("path");
const request = require('superagent'); 
const sendToWormhole = require('stream-wormhole');
const fs = require('fs');
const toArray = require('stream-to-array');
class formService extends Service {
    async index() {
        const ctx = this.ctx;
        const url = 'http://xxxxx/eggpost/';
        const stream = await ctx.getFileStream();
        const target = path.join(this.config.baseDir, 'app/public', stream.filename);
        let result;
        try {
            const parts = await toArray(stream);
            letbuf = Buffer.concat(parts); // Write the file to local fs.writeFileSync(target, buf); result = await request .post(url) .attach('file', target, stream.filename)} catch (err) {// The uploaded file stream must be consumed, otherwise the browser response will block await sendToWormhole(stream); throw err; } // Delete file fs.unlink(target,function (err) {
            if(! err) { console.log('File deleted:', target); }});return {
            result:result.text
        }
    }
}
 
module.exports = formService;
Copy the code

Python code

Directly using Django to achieve, on the code

def eggpost(request):
    if request.method == 'GET':
        pass
    else:
        try:
            files = request.FILES.getlist('file')
            for f in files:
                destination = open(os.path.join(BASE_DIR, 'static'.'images', f.name), 'wb+')
                for chunk in f.chunks():
                    destination.write(chunk)
                destination.close()
 
            msg = {
                'status': 200,
                'msg': 'Upload successful',
            }
        except Exception as e:
            print(e)
            msg = {
                'status': 500,
                'msg': 'Upload failed',}return HttpResponse(json.dumps(msg,ensure_ascii=False))
Copy the code

That’s it. It’s easy, right? In fact, I also thought about forwarding through proxy middleware, but there were some problems. The implementation principle was also forwarding interface, and there would be delays in element. After practice, I finally adopted this method.

The code looks very simple, but for some people there are still some help, also stepped on a lot of pits, and finally are still solved, there is a better way to implement please advise ~~

Later I saw someone also sent the relevant forwarding ideas, I just put my own code also posted to provide a way of thinking, don’t like it please click spray oh

A link to the

  • Juejin. Cn/post / 684490…
  • www.cnblogs.com/zzsdream/p/…