Angularjs 如何上传多部分表单数据和文件?

编程入门 行业动态 更新时间:2024-10-28 00:25:16
本文介绍了Angularjs 如何上传多部分表单数据和文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我是 angular.js 的初学者,但我对基础知识有很好的掌握.

我要做的是上传一个文件和一些表单数据作为多部分表单数据.我读到这不是 angular 的功能,但是 3rd 方库可以完成此操作.我已经通过 git 克隆了 angular-file-upload,但是我仍然无法发布一个简单的表单和文件.

有人可以提供一个例子,如何做到这一点的html和js吗?

解决方案

首先

您不需要对结构进行任何特殊更改.我的意思是:html 输入标签.

<input accept="image/*" name="file" ng-value="fileToUpload"value="{{fileToUpload}}" file-model="fileToUpload"set-file-data="fileToUpload = value;"type="file" id="my_file"/>

1.2 创建自己的指令,

.directive("fileModel",function() {返回 {限制:'EA',范围: {setFileData: "&"},链接:函数(范围,元素,属性){ele.on('改变', 函数() {范围.$应用(函数(){var val = ele[0].files[0];scope.setFileData({ value: val });});});}}})

在带有 $httpProvider 的模块中,使用 multipart/form-data 添加依赖项,例如(Accept、Content-Type 等).(建议是,接受 json 格式的响应)例如:

<块引用>

$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript';$httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data;charset=utf-8';

然后在控制器中创建单独的函数来处理表单提交调用.比如下面的代码:

在服务函数中故意处理responseType"参数,以便服务器不应该抛出byteerror".

transformRequest,修改带有附加身份的请求格式.

withCredentials : false,用于 HTTP 身份验证信息.

在控制器中://相应地对此进行编码,以便您的文件对象//将在下面的服务电话中接听.fileUpload.uploadFileToUrl(file);在役:.service('fileUpload', ['$http', 'ajaxService',功能($http,ajaxService){this.uploadFileToUrl = 函数(数据){变量数据 = {};//文件对象var fd = new FormData();fd.append('file', data.file);$http.post("发送文件的端点服务器路径", fd, {withCredentials:假,标题:{'内容类型':未定义},变换请求:angular.identity,参数:{FD},响应类型:数组缓冲区"}).then(功能(响应){var data = response.data;var status = response.status;控制台日志(数据);if (status == 200 || status == 202)//做任何成功的事else//如果需要,处理 else 中的错误}).catch(函数(错误){控制台日志(错误.状态);//处理其他调用});}}}])

<script src="//unpkg/angular/angular.js"></script>

I'm a beginner to angular.js but I have a good grasp of the basics.

What I am looking to do is upload a file and some form data as multipart form data. I read that this isn't a feature of angular, however 3rd party libraries can get this done. I've cloned angular-file-upload via git, however I am still unable to post a simple form and a file.

Can someone please provide an example, html and js of how to do this?

解决方案

First of all

You don't need any special changes in the structure. I mean: html input tags.

<input accept="image/*" name="file" ng-value="fileToUpload"
       value="{{fileToUpload}}" file-model="fileToUpload"
       set-file-data="fileToUpload = value;" 
       type="file" id="my_file" />

1.2 create own directive,

.directive("fileModel",function() {
	return {
		restrict: 'EA',
		scope: {
			setFileData: "&"
		},
		link: function(scope, ele, attrs) {
			ele.on('change', function() {
				scope.$apply(function() {
					var val = ele[0].files[0];
					scope.setFileData({ value: val });
				});
			});
		}
	}
})

In module with $httpProvider add dependency like ( Accept, Content-Type etc) with multipart/form-data. (Suggestion would be, accept response in json format) For e.g:

$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';

Then create separate function in controller to handle form submit call. like for e.g below code:

In service function handle "responseType" param purposely so that server should not throw "byteerror".

transformRequest, to modify request format with attached identity.

withCredentials : false, for HTTP authentication information.

in controller:

  // code this accordingly, so that your file object 
  // will be picked up in service call below.
  fileUpload.uploadFileToUrl(file); 


in service:

  .service('fileUpload', ['$http', 'ajaxService',
    function($http, ajaxService) {

      this.uploadFileToUrl = function(data) {
        var data = {}; //file object 

        var fd = new FormData();
        fd.append('file', data.file);

        $http.post("endpoint server path to whom sending file", fd, {
            withCredentials: false,
            headers: {
              'Content-Type': undefined
            },
            transformRequest: angular.identity,
            params: {
              fd
            },
            responseType: "arraybuffer"
          })
          .then(function(response) {
            var data = response.data;
            var status = response.status;
            console.log(data);

            if (status == 200 || status == 202) //do whatever in success
            else // handle error in  else if needed 
          })
          .catch(function(error) {
            console.log(error.status);

            // handle else calls
          });
      }
    }
  }])

<script src="//unpkg/angular/angular.js"></script>

这篇关于Angularjs 如何上传多部分表单数据和文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 08:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1019726.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   上传   文件   数据   Angularjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!