Angular를 사용한 파일 업로드JS
HTML 폼은 다음과 같습니다.
<form name="myForm" ng-submit="">
<input ng-model='file' type="file"/>
<input type="submit" value='Submit'/>
</form>
로컬 머신에서 이미지를 업로드하고 업로드한 파일의 내용을 읽고 싶습니다.Angular를 사용하여 이 모든 것을 하고 싶다.JS.
★★★★★★★★★★★★★★★의 값을 인쇄하려고 하면,$scope.file
정의되지 않은 것으로 나타납니다.
에서는 이렇게 '', '아까', '아까', '아까', '아까', '아까', '아까', '아까',FormData()
, Internet 할 수 없는 브라우저를 를 들어, 「」를 사용합니다.<iframe>
는는플플 플다다다다다
파일 업로드를 실행하는 Angular.js 모듈은 이미 많이 있습니다.이들 2개는 오래된 브라우저를 명시적으로 지원합니다.
- https://github.com/leon/angular-upload - iframe을 폴백으로 사용합니다.
- https://github.com/danialfarid/ng-file-upload - File API/Flash를 폴백으로 사용
기타 옵션:
- https://github.com/nervgh/angular-file-upload/
- https://github.com/uor/angular-file
- https://github.com/twilson63/ngUpload
- https://github.com/uploadcare/angular-uploadcare
이 중 하나가 프로젝트에 적합하거나 직접 코드화하는 방법에 대한 통찰력을 얻을 수 있습니다.
가장 쉬운 것은 HTML5 API를 사용하는 것입니다.
HTML은 매우 간단합니다.
<input type="file" id="file" name="file"/>
<button ng-click="add()">Add</button>
컨트롤러에서 '추가' 방식을 정의합니다.
$scope.add = function() {
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function(e) {
var data = e.target.result;
//send your binary data via $http or $resource or do anything else with it
}
r.readAsBinaryString(f);
}
브라우저 호환성
데스크톱 브라우저
Edge 12, Firefox(Gecko) 3.6(1.9.2), Chrome 7, Opera*12.02, Safari 6.0.2
모바일 브라우저
파이어폭스(Gecko) 32, Chrome 3, Opera* 11.5, Safari 6.1
주의: readAsBinaryString() 메서드는 권장되지 않으며 readAs입니다.대신 ArrayBuffer()를 사용해야 합니다.
이것은 서드파티 라이브러리가 없는 현대적인 브라우저 방식입니다.모든 최신 브라우저에서 작동합니다.
app.directive('myDirective', function (httpPostFactory) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attr) {
element.bind('change', function () {
var formData = new FormData();
formData.append('file', element[0].files[0]);
httpPostFactory('upload_image.php', formData, function (callback) {
// recieve image name to use in a ng-src
console.log(callback);
});
});
}
};
});
app.factory('httpPostFactory', function ($http) {
return function (file, data, callback) {
$http({
url: file,
method: "POST",
data: data,
headers: {'Content-Type': undefined}
}).success(function (response) {
callback(response);
});
};
});
HTML:
<input data-my-Directive type="file" name="file">
PHP:
if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
// uploads image in the folder images
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = substr(md5(time()), 0, 10) . '.' . end($temp);
move_uploaded_file($_FILES['file']['tmp_name'], 'images/' . $newfilename);
// give callback to your angular code with the image src name
echo json_encode($newfilename);
}
js findle (프런트 엔드만)https://jsfiddle.net/vince123/8d18tsey/31/
다음은 파일 업로드의 작업 예입니다.
http://jsfiddle.net/vishalvasani/4hqVu/
이 기능에서는
setFiles
[From View] : 컨트롤러의 파일 어레이를 갱신합니다.
또는
각도를 사용하여 jQuery 파일 업로드를 확인할 수 있습니다.JS
http://blueimp.github.io/jQuery-File-Upload/angularjs.html
flow.js를 사용하면 파일 및 폴더 업로드를 원활하게 수행할 수 있습니다.
https://github.com/flowjs/ng-flow
데모를 보려면 여기를 클릭하십시오.
http://flowjs.github.io/ng-flow/
IE7, IE8 및 IE9를 지원하지 않으므로 최종적으로는 호환성 계층을 사용해야 합니다.
https://github.com/flowjs/fusty-flow.js
하다를 사용하세요.onchange
를 function에 전달하는 이벤트입니다.
<input type="file" onchange="angular.element(this).scope().fileSelected(this)" />
따라서 사용자가 파일을 선택할 때 "추가" 또는 "업로드" 버튼을 클릭할 필요 없이 파일에 대한 참조가 제공됩니다.
$scope.fileSelected = function (element) {
var myFileSelected = element.files[0];
};
@Anoyz(정답)가 주는 모든 대안을 시도해 보았다.최고의 솔루션은 https://github.com/danialfarid/angular-file-upload 입니다.
일부 기능:
- 진보.
- 멀티파일
- 필드
- 오래된 브라우저(IE8-9)
저는 괜찮습니다.당신은 단지 지시사항에 주의를 기울이면 됩니다.
서버 측에서는 NodeJs, Express 4 및 Multer 미들웨어를 사용하여 멀티파트 요청을 관리합니다.
HTML
<html>
<head></head>
<body ng-app = "myApp">
<form ng-controller = "myCtrl">
<input type = "file" file-model="files" multiple/>
<button ng-click = "uploadFile()">upload me</button>
<li ng-repeat="file in files">{{file.name}}</li>
</form>
스크립트
<script src =
"http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
angular.module('myApp', []).directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('change', function(){
$parse(attrs.fileModel).assign(scope,element[0].files)
scope.$apply();
});
}
};
}]).controller('myCtrl', ['$scope', '$http', function($scope, $http){
$scope.uploadFile=function(){
var fd=new FormData();
console.log($scope.files);
angular.forEach($scope.files,function(file){
fd.append('file',file);
});
$http.post('http://localhost:1337/mediaobject/upload',fd,
{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function(d)
{
console.log(d);
})
}
}]);
</script>
<input type=file>
요소는 기본적으로는 ng-model 디렉티브에서는 동작하지 않습니다.커스텀 디렉티브가 필요합니다.
★★★★의 작업 select-ng-files
「」와 ng-model
1
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileList" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileList">
{{file.name}}
</div>
</body>
$http.post
File List에서
$scope.upload = function(url, fileList) {
var config = { headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
var promises = fileList.map(function(file) {
return $http.post(url, file, config);
});
return $q.all(promises);
};
파일 오브젝트와 함께 POST를 송신할 때는,'Content-Type': undefined
그러면 XHR 전송 메서드가 File 객체를 검출하고 콘텐츠 유형을 자동으로 설정합니다.
지시가 간단
HTML:
<input type="file" file-upload multiple/>
JS:
app.directive('fileUpload', function () {
return {
scope: true, //create a new scope
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var files = event.target.files;
//iterate files since 'multiple' may be specified on the element
for (var i = 0;i<files.length;i++) {
//emit event upward
scope.$emit("fileSelected", { file: files[i] });
}
});
}
};
지시문에서는 새로운 스코프가 작성되었는지 확인하고 파일 입력 요소에 대한 변경 사항을 확인합니다.에서 변경이 검출되면 파일개체를 파라미터로 하여 모든 상위 스코프(상위)에 이벤트를 송신합니다.
컨트롤러 내:
$scope.files = [];
//listen for the file selected event
$scope.$on("fileSelected", function (event, args) {
$scope.$apply(function () {
//add the file object to the scope's files collection
$scope.files.push(args.file);
});
});
그런 다음 Ajax 콜:
data: { model: $scope.model, files: $scope.files }
http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/
각진 파일 업로드가 다음과 같습니다.
ng-file-displayed(파일 변환)
파일을 업로드하는 Lightweight Angular JS 지시어.
DEMO 페이지입니다.특징들
- 업로드 진행 상황, 업로드 취소/중지, 파일 드래그 앤 드롭(html5, 디렉토리 드래그 앤 드롭(webkit), CORS, PUT(html5)/POST 메서드, 파일 유형과 크기 검증, 선택한 이미지/오디오/비디오 미리보기 표시 지원
- Flash polyfill FileAPI를 사용하는 크로스 브라우저 파일 업로드 및 FileReader(HTML5 및 비HTML5)파일을 업로드하기 전에 클라이언트 측 검증/수정 허용
- db 서비스 CouchDB, imgur 등에 직접 업로드...Upload.http()를 사용하여 파일의 콘텐츠 유형을 지정합니다.이것에 의해, 각도 http POST/PUT 요구의 프로그레스 이벤트가 유효하게 됩니다.
- 별도의 shim 파일, FileAPI 파일은 HTML5 이외의 코드에 대한 요구에 따라 로드되므로 HTML5 지원만 필요한 경우 추가 로드/코드가 없습니다.
- 일반 $http를 사용하여 업로드(HTML5 이외의 브라우저의 경우 shim 포함)하여 모든 각도 $http 기능을 사용할 수 있습니다.
https://github.com/danialfarid/ng-file-upload
파일과 json 데이터가 동시에 업로드 됩니다.
// FIRST SOLUTION
var _post = function (file, jsonData) {
$http({
url: your url,
method: "POST",
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
formData.append("file", data.files);
return formData;
},
data: { model: jsonData, files: file }
}).then(function (response) {
;
});
}
// END OF FIRST SOLUTION
// SECOND SOLUTION
// If you can add plural file and If above code give an error.
// You can try following code
var _post = function (file, jsonData) {
$http({
url: your url,
method: "POST",
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
for (var i = 0; i < data.files.length; i++) {
// add each file to
// the form data and iteratively name them
formData.append("file" + i, data.files[i]);
}
return formData;
},
data: { model: jsonData, files: file }
}).then(function (response) {
;
});
}
// END OF SECOND SOLUTION
'어울리다'를 사용할 수 요.FormData
"CHANGE: " "CHANGE: "CHANGE:
// Store the file object when input field is changed
$scope.contentChanged = function(event){
if (!event.files.length)
return null;
$scope.content = new FormData();
$scope.content.append('fileUpload', event.files[0]);
$scope.$apply();
}
// Upload the file over HTTP
$scope.upload = function(){
$http({
method: 'POST',
url: '/remote/url',
headers: {'Content-Type': undefined },
data: $scope.content,
}).success(function(response) {
// Uploading complete
console.log('Request finished', response);
});
}
http://jsfiddle.net/vishalvasani/4hqVu/ 는, Chrome 와 IE 로 정상적으로 동작합니다(배경 이미지로 CSS 를 조금 갱신하면).진행률 표시줄 업데이트에 사용됩니다.
scope.progress = Math.round(evt.loaded * 100 / evt.total)
그러나 FireFox angular의 [percent]데이터는 DOM에서 정상적으로 갱신되지 않습니다만, 파일은 정상적으로 업 로드되고 있습니다.
Uploadcare 등의 파일 업로드에 IaaS를 고려할 수 있습니다.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/
늦은 입력인 것은 알지만 간단한 업로드 지시문을 작성했습니다.금방 일을 할 수 있을 거야!
<input type="file" multiple ng-simple-upload web-api-url="/api/Upload" callback-fn="myCallback" />
ng-simple-upload는 웹 API를 사용한 예시와 함께 Github에 더 많이 업로드합니다.
HTML
<input type="file" id="file" name='file' onchange="angular.element(this).scope().profileimage(this)" />
컨트롤러에 'profileimage()' 메서드를 추가합니다.
$scope.profileimage = function(selectimage) {
console.log(selectimage.files[0]);
var selectfile=selectimage.files[0];
r = new FileReader();
r.onloadend = function (e) {
debugger;
var data = e.target.result;
}
r.readAsBinaryString(selectfile);
}
이것은 @jquery-guru의 답변에 대한 업데이트/댓글이 될 것입니다만, 제 답변이 부족하기 때문에 여기로 이동합니다.현재 코드에 의해 생성된 오류를 수정합니다.
https://jsfiddle.net/vzhrqotw/
기본적으로 다음과 같은 변경이 있습니다.
FileUploadCtrl.$inject = ['$scope']
function FileUploadCtrl(scope) {
수신인:
app.controller('FileUploadCtrl', function($scope)
{
원하는 경우 더 적절한 위치로 이동해도 됩니다.
모든 스레드를 읽었는데 HTML5 API 솔루션이 가장 좋아 보였어요.하지만 내가 조사하지 않은 방식으로 내 바이너리 파일을 바꿔서 망가뜨거워져.나에게 딱 맞는 솔루션은 다음과 같습니다.
HTML:
<input type="file" id="msds" ng-model="msds" name="msds"/>
<button ng-click="msds_update()">
Upload
</button>
JS:
msds_update = function() {
var f = document.getElementById('msds').files[0],
r = new FileReader();
r.onloadend = function(e) {
var data = e.target.result;
console.log(data);
var fd = new FormData();
fd.append('file', data);
fd.append('file_name', f.name);
$http.post('server_handler.php', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
console.log('success');
})
.error(function(){
console.log('error');
});
};
r.readAsDataURL(f);
}
서버측(PHP):
$file_content = $_POST['file'];
$file_content = substr($file_content,
strlen('data:text/plain;base64,'));
$file_content = base64_decode($file_content);
Angular를 사용하여 파일을 업로드할 수 있습니다.다음 코드를 사용하여 JS:
file
ngUploadFileUpload
$scope.file
질문하신 대로입니다.
는 ''를 사용하는 입니다.transformRequest: []
이렇게 하면 $http가 파일 내용을 망치는 것을 방지할 수 있습니다.
function getFileBuffer(file) {
var deferred = new $q.defer();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise;
}
function ngUploadFileUpload(endPointUrl, file) {
var deferred = new $q.defer();
getFileBuffer(file).then(function (arrayBuffer) {
$http({
method: 'POST',
url: endPointUrl,
headers: {
"accept": "application/json;odata=verbose",
'X-RequestDigest': spContext.securityValidation,
"content-length": arrayBuffer.byteLength
},
data: arrayBuffer,
transformRequest: []
}).then(function (data) {
deferred.resolve(data);
}, function (error) {
deferred.reject(error);
console.error("Error", error)
});
}, function (error) {
console.error("Error", error)
});
return deferred.promise;
}
위의 답변은 브라우저와 호환되지 않습니다.호환성에 문제가 있는 경우는, 이것을 사용해 주세요.
코드 표시
<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);
}
}
간단히 말하면
HTML - 아래 코드만 추가
<form name="upload" class="form" data-ng-submit="addFile()">
<input type="file" name="file" multiple
onchange="angular.element(this).scope().uploadedFile(this)" />
<button type="submit">Upload </button>
</form>
컨트롤러 - "파일 업로드 버튼"을 클릭하면 이 기능이 호출됩니다.파일이 업로드 됩니다.위로할 수 있어요
$scope.uploadedFile = function(element) {
$scope.$apply(function($scope) {
$scope.files = element.files;
});
}
add more in controller - 아래 코드 add in 함수에 추가합니다."Hiting the api (POST)" 버튼을 클릭하면 이 함수가 호출되며 파일(업로드)과 폼데이터를 백엔드로 전송합니다.
var url = httpURL + "/reporttojson"
var files=$scope.files;
for ( var i = 0; i < files.length; i++)
{
var fd = new FormData();
angular.forEach(files,function(file){
fd.append('file',file);
});
var data ={
msg : message,
sub : sub,
sendMail: sendMail,
selectUsersAcknowledge:false
};
fd.append("data", JSON.stringify(data));
$http.post(url, fd, {
withCredentials : false,
headers : {
'Content-Type' : undefined
},
transformRequest : angular.identity
}).success(function(data)
{
toastr.success("Notification sent successfully","",{timeOut: 2000});
$scope.removereport()
$timeout(function() {
location.reload();
}, 1000);
}).error(function(data)
{
toastr.success("Error in Sending Notification","",{timeOut: 2000});
$scope.removereport()
});
}
이 경우에는..폼 데이터로 아래 코드를 추가했습니다.
var data ={
msg : message,
sub : sub,
sendMail: sendMail,
selectUsersAcknowledge:false
};
<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>
비스듬히JS 컨트롤러
$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;
}
HTML, CSS, Angular를 사용했습니다.JS. 다음 예시는 Angular를 사용하여 파일을 업로드하는 방법을 보여 줍니다.JS.
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.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(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>
Simple Directive(ng-file-model)를 사용한 작업 예:
.directive("ngFileModel", [function () {
return {
$scope: {
ngFileModel: "="
},
link: function ($scope:any, element, attributes) {
element.bind("change", function (changeEvent:any) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
$scope.$apply(function () {
$scope.ngFileModel = {
lastModified: changeEvent.target.files[0].lastModified,
lastModifiedDate: changeEvent.target.files[0].lastModifiedDate,
name: changeEvent.target.files[0].name,
size: changeEvent.target.files[0].size,
type: changeEvent.target.files[0].type,
data: changeEvent.target.files[0]
};
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}])
및 사용FormData
파일을 업로드 할 수 있습니다.
var formData = new FormData();
formData.append("document", $scope.ngFileModel.data)
formData.append("user_id", $scope.userId)
모든 크레딧은 https://github.com/mistralworks/ng-file-model에 적용됩니다.
작은 문제에 직면해 있습니다.https://github.com/mistralworks/ng-file-model/issues/7 에서 확인하실 수 있습니다.
마지막으로, https://github.com/okasha93/ng-file-model/blob/patch-1/ng-file-model.js라는 분기된 보고서가 있습니다.
코드는 파일 삽입에 도움이 됩니다.
<body ng-app = "myApp">
<form ng-controller="insert_Ctrl" method="post" action="" name="myForm" enctype="multipart/form-data" novalidate>
<div>
<p><input type="file" ng-model="myFile" class="form-control" onchange="angular.element(this).scope().uploadedFile(this)">
<span style="color:red" ng-show="(myForm.myFile.$error.required&&myForm.myFile.$touched)">Select Picture</span>
</p>
</div>
<div>
<input type="button" name="submit" ng-click="uploadFile()" class="btn-primary" ng-disabled="myForm.myFile.$invalid" value="insert">
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="insert.js"></script>
</body>
insert.insert.displaces
var app = angular.module('myApp',[]);
app.service('uploadFile', ['$http','$window', function ($http,$window) {
this.uploadFiletoServer = function(file,uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(data){
alert("insert successfull");
$window.location.href = ' ';//your window location
})
.error(function(){
alert("Error");
});
}
}]);
app.controller('insert_Ctrl', ['$scope', 'uploadFile', function($scope, uploadFile){
$scope.uploadFile = function() {
$scope.myFile = $scope.files[0];
var file = $scope.myFile;
var url = "save_data.php";
uploadFile.uploadFiletoServer(file,url);
};
$scope.uploadedFile = function(element) {
var reader = new FileReader();
reader.onload = function(event) {
$scope.$apply(function($scope) {
$scope.files = element.files;
$scope.src = event.target.result
});
}
reader.readAsDataURL(element.files[0]);
}
}]);
save_data.php
<?php
require "dbconnection.php";
$ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
$image = time().'.'.$ext;
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$image);
$query="insert into test_table values ('null','$image')";
mysqli_query($con,$query);
?>
이것은 효과가 있다
file.filength.filength 파일
<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.controller.controllers
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>
파일을 업로드 합니다.php
<?php
$ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
$image = time().'.'.$ext;
move_uploaded_file($_FILES["file"]["tmp_name"],__DIR__. ' \\'.$image);
?>
파일 업로드
<input type="file" name="resume" onchange="angular.element(this).scope().uploadResume()" ng-model="fileupload" id="resume" />
$scope.uploadResume = function () {
var f = document.getElementById('resume').files[0];
$scope.selectedResumeName = f.name;
$scope.selectedResumeType = f.type;
r = new FileReader();
r.onloadend = function (e) {
$scope.data = e.target.result;
}
r.readAsDataURL(f);
};
파일 다운로드:
<a href="{{applicant.resume}}" download> download resume</a>
var app = angular.module("myApp", []);
app.config(['$compileProvider', function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|local|data|chrome-extension):/);
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|local|data|chrome-extension):/);
}]);
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) { }
언급URL : https://stackoverflow.com/questions/18571001/file-upload-using-angularjs
'programing' 카테고리의 다른 글
잭슨과의 불변의 롬복 주석 클래스 (0) | 2023.03.09 |
---|---|
create-react-app은 언제 코드를 난독화 또는 최소화합니까? (0) | 2023.03.04 |
클릭: 작동하지 않음 반응 js (0) | 2023.03.04 |
WordPress 쇼트 코드 내에서 자동 서식 사용 안 함 (0) | 2023.03.04 |
의존성 주입 용기의 이점은 무엇입니까? (0) | 2023.03.04 |