微信小程序大文件上传及django后台接收文件

融唯
2023-12-01

1.使用微信小程序的插件miniprogram-file-uploader

2.构建安装插件miniprogram-file-uploader

npm i miniprogram-file-uploader

3.微信小程序中js中的写法

引入插件

    import Uploader from 'miniprogram-file-uploader';
    var image_uploadUrl = 'http://127.0.0.1:8888/api/upload_image/'
    var  image_mergeUrl = 'http://127.0.0.1:8888/api/merge_image/'
    const uploader = new Uploader({
                tempFilePath:image_filePath, #文件的临时路径
                fileName: fileName, #文件名称
                totalSize: image_fileSize, #文件总的大小
                chunkSize:parseInt(image_fileSize/5), #一次上传文件多少字节,
                maxConcurrency:5, # 并发数量,最大数量为10,默认为5
                header:{'Content-Type':'application/octet-stream'},
                query:{'openid':this.data.openId}, #需要填入的其他参数
                uploadUrl: image_uploadUrl, # 文件上传接口
                mergeUrl: image_mergeUrl,  #文件合并接口
                verbose:'true', #日志输出
            });
            uploader.upload();
            uploader.on('success', (res) => {
                 console.log('upload success', res) #上传成功,返回参数
            }
        )

4.django后台接收方式

def merge_image(request):
    '''
    合并文件
    :param request:
    :return:
    '''
    identifier = request.GET.get('identifier')
    filename = request.GET.get('fileName')
    path = os.path.join(os.getcwd(), 'upload', 'original_image', identifier)
    file_list = os.listdir(path)
    file_list.sort()
    with open(os.path.join(os.getcwd(), 'upload', 'original_image', f'{filename}.jpg'), 'ab') as f:
        for i in file_list:
            with open(os.path.join(path, i), 'rb') as fr:
                f.write(fr.read())
                fr.close()
        f.close()
    shutil.rmtree(path)
    return JsonResponse({
        'code':200,
        'url':filename,
    })

@csrf_exempt
def upload_image(request):
    '''
    分片文件保存到服务器    
    :param request:
    :return:
    '''
    identifier = request.GET.get('identifier') #md5文件标识
    index = request.GET.get('index') #文件分片索引
    path = os.path.join(os.getcwd(), 'upload', 'original_image') #文件路径
    out_path = os.path.join(path, identifier)
    if not os.path.exists(out_path):
        os.makedirs(out_path)
    with open(f'{out_path}/{identifier}-{index}', 'wb') as f: #保存到服务器
        f.write(request.body)
    return JsonResponse({
        'code':200
    })

 类似资料: