Angularjs $http 发布文件和表单数据 [英] Angularjs $http post file and form data

查看:29
本文介绍了Angularjs $http 发布文件和表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中有以下请求

I have the below request in python

import requests, json, io

cookie = {}
payload = {"Name":"abc"}
url = "/test"
file = "out/test.json"

fi = {'file': ('file', open(file) )}
r = requests.post("http://192.168.1.1:8080" + url, data=payload, files=fi, cookies=cookie)
print(r.text)

将文件和表单字段发送到后端.如何使用 Angular $http 执行相同的操作(发送文件 + 表单字段).目前,我喜欢这个,但不知道如何发送文件.

which send a file, and form fields to the backend. How can I do the same (sending file + form fields) with Angular $http. Currently, I do like this, but not sure how to send the file too.

var payload = {"Name":"abc"};
$http.post('/test', payload)
    .success(function (res) {
    //success
});

推荐答案

我最近编写了一个支持原生多文件上传的指令.我创建的解决方案依赖于一项服务来填补您使用 $http 服务确定的空白.我还包含了一个指令,它为您的 angular 模块提供了一个简单的 API,用于发布文件和数据.

I recently wrote a directive that supports native multiple file uploads. The solution I've created relies on a service to fill the gap you've identified with the $http service. I've also included a directive, which provides an easy API for your angular module to use to post the files and data.

示例用法:

<lvl-file-upload
    auto-upload='false'
    choose-file-button-text='Choose files'
    upload-file-button-text='Upload files'
    upload-url='http://localhost:3000/files'
    max-files='10'
    max-file-size-mb='5'
    get-additional-data='getData(files)'
    on-done='done(files, data)'
    on-progress='progress(percentDone)'
    on-error='error(files, type, msg)'/>

您可以在 github 上找到代码,以及关于我的博客

You can find the code on github, and the documentation on my blog

在您的 Web 框架中处理文件取决于您,但我创建的解决方案提供了角度接口来将数据发送到您的服务器.你需要写的angular代码是响应上传事件

It would be up to you to process the files in your web framework, but the solution I've created provides the angular interface to getting the data to your server. The angular code you need to write is to respond to the upload events

angular
    .module('app', ['lvl.directives.fileupload'])
    .controller('ctl', ['$scope', function($scope) {
        $scope.done = function(files,data} { /*do something when the upload completes*/ };
        $scope.progress = function(percentDone) { /*do something when progress is reported*/ };
        $scope.error = function(file, type, msg) { /*do something if an error occurs*/ };
        $scope.getAdditionalData = function() { /* return additional data to be posted to the server*/ };

    });

这篇关于Angularjs $http 发布文件和表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆