这是我的HTML表单:
<form name="myForm" ng-submit="">
<input ng-model='file' type="file"/>
<input type="submit" value='Submit'/>
</form>
我想从本地机器上传一个图像,并想读取上传文件的内容。所有这些我都想用AngularJS来做。
当我试图打印$scope的值时。文件是未定义的。
这是我的HTML表单:
<form name="myForm" ng-submit="">
<input ng-model='file' type="file"/>
<input type="submit" value='Submit'/>
</form>
我想从本地机器上传一个图像,并想读取上传文件的内容。所有这些我都想用AngularJS来做。
当我试图打印$scope的值时。文件是未定义的。
当前回答
<form id="csv_file_form" ng-submit="submit_import_csv()" method="POST" enctype="multipart/form-data">
<input ng-model='file' type="file"/>
<input type="submit" value='Submit'/>
</form>
在angularJS控制器中
$scope.submit_import_csv = function(){
var formData = new FormData(document.getElementById("csv_file_form"));
console.log(formData);
$.ajax({
url: "import",
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(result, textStatus, jqXHR)
{
console.log(result);
}
});
return false;
}
其他回答
以上接受的答案不兼容浏览器。如果有人有兼容性问题,试试这个。
小提琴
视图代码
<div ng-controller="MyCtrl">
<input type="file" id="file" name="file"/>
<br>
<button ng-click="add()">Add</button>
<p>{{data}}</p>
</div>
控制器代码
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.data = 'none';
$scope.add = function(){
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function(e){
var binary = "";
var bytes = new Uint8Array(e.target.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++)
{
binary += String.fromCharCode(bytes[i]);
}
$scope.data = (binary).toString();
alert($scope.data);
}
r.readAsArrayBuffer(f);
}
}
您可以考虑使用IaaS进行文件上传,例如Uploadcare。有一个针对它的Angular包:https://github.com/uploadcare/angular-uploadcare
从技术上讲,它被实现为一个指令,提供了不同的上传选项,以及小部件中上传图像的操作:
<uploadcare-widget
ng-model="object.image.info.uuid"
data-public-key="YOURKEYHERE"
data-locale="en"
data-tabs="file url"
data-images-only="true"
data-path-value="true"
data-preview-step="true"
data-clearable="true"
data-multiple="false"
data-crop="400:200"
on-upload-complete="onUCUploadComplete(info)"
on-widget-ready="onUCWidgetReady(widget)"
value="{{ object.image.info.cdnUrl }}"
/>
更多配置选项:https://uploadcare.com/widget/configure/
我尝试了@ anoz(正确答案)给出的所有替代方案…最好的解决方案是https://github.com/danialfarid/angular-file-upload
一些特点:
进步 多文件 字段 旧浏览器(IE8-9)
这对我来说很好。你只需要注意说明。
在服务器端,我使用NodeJs, Express 4和Multer中间件来管理多部分请求。
这是
file.html
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "app">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
</body>
<script src="controller.js"></script>
</html>
controller.js
var app = angular.module('app', []);
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function(res){
console.log(res);
}).error(function(error){
console.log(error);
});
}
}]);
app.controller('fileCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload.php"; // upload url stands for api endpoint to handle upload to directory
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
fileupload.php
<?php
$ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
$image = time().'.'.$ext;
move_uploaded_file($_FILES["file"]["tmp_name"],__DIR__. ' \\'.$image);
?>
app.directive('ngUpload', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var options = {};
options.enableControls = attrs['uploadOptionsEnableControls'];
// get scope function to execute on successful form upload
if (attrs['ngUpload']) {
element.attr("target", "upload_iframe");
element.attr("method", "post");
// Append a timestamp field to the url to prevent browser caching results
element.attr("action", element.attr("action") + "?_t=" + new Date().getTime());
element.attr("enctype", "multipart/form-data");
element.attr("encoding", "multipart/form-data");
// Retrieve the callback function
var fn = attrs['ngUpload'].split('(')[0];
var callbackFn = scope.$eval(fn);
if (callbackFn == null || callbackFn == undefined || !angular.isFunction(callbackFn))
{
var message = "The expression on the ngUpload directive does not point to a valid function.";
// console.error(message);
throw message + "\n";
}
// Helper function to create new i frame for each form submission
var addNewDisposableIframe = function (submitControl) {
// create a new iframe
var iframe = $("<iframe id='upload_iframe' name='upload_iframe' border='0' width='0' height='0' style='width: 0px; height: 0px;
border: none; display: none' />");
// attach function to load event of the iframe
iframe.bind('load', function () {
// get content - requires jQuery
var content = iframe.contents().find('body').text();
// execute the upload response function in the active scope
scope.$apply(function () { callbackFn(content, content !== "" /* upload completed */); });
// remove iframe
if (content != "") // Fixes a bug in Google Chrome that dispose the iframe before content is ready.
setTimeout(function () { iframe.remove(); }, 250);
submitControl.attr('disabled', null);
submitControl.attr('title', 'Click to start upload.');
});
// add the new iframe to application
element.parent().append(iframe);
};
// 1) get the upload submit control(s) on the form (submitters must be decorated with the 'ng-upload-submit' class)
// 2) attach a handler to the controls' click event
$('.upload-submit', element).click(
function () {
addNewDisposableIframe($(this) /* pass the submit control */);
scope.$apply(function () { callbackFn("Please wait...", false /* upload not completed */); });
var enabled = true;
if (options.enableControls === null || options.enableControls === undefined || options.enableControls.length >= 0) {
// disable the submit control on click
$(this).attr('disabled', 'disabled');
enabled = false;
}
$(this).attr('title', (enabled ? '[ENABLED]: ' : '[DISABLED]: ') + 'Uploading, please wait...');
// submit the form
$(element).submit();
}
).attr('title', 'Click to start upload.');
}
else
alert("No callback function found on the ngUpload directive.");
}
};
});
<form class="form form-inline" name="uploadForm" id="uploadForm"
ng-upload="uploadForm12" action="rest/uploadHelpFile" method="post"
enctype="multipart/form-data" style="margin-top: 3px;margin-left:
6px"> <button type="submit" id="mbUploadBtn" class="upload-submit"
ng-hide="true"></button> </form>
@RequestMapping(value = "/uploadHelpFile", method =
RequestMethod.POST) public @ResponseBody String
uploadHelpFile(@RequestParam(value = "file") CommonsMultipartFile[]
file,@RequestParam(value = "fileName") String
fileName,@RequestParam(value = "helpFileType") String
helpFileType,@RequestParam(value = "helpFileName") String
helpFileName) { }