Angular의 다른 필드와 함께 FormData 전송JS
두 장짜리 폼이 있어요.input text
그리고 하나upload
서버에 보내야 하는데 파일과 텍스트를 연결하는 데 문제가 있습니다.서버는 다음과 같은 응답을 예상하고 있습니다.
"title=first_input" "text=second_input" "file=my_file.pdf"
html은 다음과 같습니다.
<input type="text" ng-model="title">
<input type="text" ng-model="text">
<input type="file" file-model="myFile"/>
<button ng-click="send()">
컨트롤러는 다음과 같습니다.
$scope.title = null;
$scope.text = null;
$scope.send = function(){
var file = $scope.myFile;
var uploadUrl = 'my_url';
blockUI.start();
Add.uploadFileToUrl(file, $scope.newPost.title, $scope.newPost.text, uploadUrl);
};
Directive file Model은 다음과 같습니다.
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]);
});
});
}
};
이 서비스는 서버를 호출합니다.
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var fd = new FormData();
fd.append('file', file);
var obj = {
title: title,
text: text,
file: fd
};
var newObj = JSON.stringify(obj);
$http.post(uploadUrl, newObj, {
transformRequest: angular.identity,
headers: {'Content-Type': 'multipart/form-data'}
})
.success(function(){
blockUI.stop();
})
.error(function(error){
toaster.pop('error', 'Errore', error);
});
}
송신하려고 하면, Error 400 이라고 표시됩니다.응답은 다음과 같습니다.Multipart form parse error - Invalid boundary in multipart: None
. 요청의 payload는 다음과 같습니다.{"title":"sadf","text":"sdfsadf","file":{}}
직렬화 안 함FormData
와 함께POST
서버에 접속합니다.다음을 수행합니다.
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var payload = new FormData();
payload.append("title", title);
payload.append('text', text);
payload.append('file', file);
return $http({
url: uploadUrl,
method: 'POST',
data: payload,
//assign content-type as undefined, the browser
//will assign the correct boundary for us
headers: { 'Content-Type': undefined},
//prevents serializing payload. don't do it.
transformRequest: angular.identity
});
}
그 후 사용합니다.
MyService.uploadFileToUrl(file, title, text, uploadUrl).then(successCallback).catch(errorCallback);
여기 완전한 솔루션이 있습니다.
html 코드,
다음과 같은 텍스트 anf 파일 업로드 필드를 만듭니다.
<div class="form-group">
<div>
<label for="usr">User Name:</label>
<input type="text" id="usr" ng-model="model.username">
</div>
<div>
<label for="pwd">Password:</label>
<input type="password" id="pwd" ng-model="model.password">
</div><hr>
<div>
<div class="col-lg-6">
<input type="file" file-model="model.somefile"/>
</div>
</div>
<div>
<label for="dob">Dob:</label>
<input type="date" id="dob" ng-model="model.dob">
</div>
<div>
<label for="email">Email:</label>
<input type="email"id="email" ng-model="model.email">
</div>
<button type="submit" ng-click="saveData(model)" >Submit</button>
지시 코드
파일을 구문 분석할 파일 모델 지시문 생성
.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]);
});
});
}
};}]);
서비스 코드
파일 및 필드를 추가하여 데이터를 생성하고 $disclosing을 수행합니다.아래 표시된 게시물은 'Content-Type'을 유지해야 합니다: 정의되지 않았습니다.
.service('fileUploadService', ['$http', function ($http) {
this.uploadFileToUrl = function(file, username, password, dob, email, uploadUrl){
var myFormData = new FormData();
myFormData.append('file', file);
myFormData.append('username', username);
myFormData.append('password', password);
myFormData.append('dob', dob);
myFormData.append('email', email);
$http.post(uploadUrl, myFormData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
인컨트롤러
이제 컨트롤러는 파라미터에 부가되는 필수 데이터를 전송하여 서비스를 호출합니다.
$scope.saveData = function(model){
var file = model.myFile;
var uploadUrl = "/api/createUsers";
fileUpload.uploadFileToUrl(file, model.username, model.password, model.dob, model.email, uploadUrl);
};
JSON 형식의 데이터를 해당 형식을 필요로 하지 않는 서버로 보내고 있습니다.서버에 필요한 포맷을 이미 제공했기 때문에 사용자가 직접 포맷해야 합니다.이것은 매우 간단합니다.
var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)
이렇게 하면 FormData 개체를 문자열화할 수 없습니다.
다음 작업을 수행해야 합니다.
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var fd = new FormData();
fd.append('title', title);
fd.append('text', text);
fd.append('file', file);
$http.post(uploadUrl, obj, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
blockUI.stop();
})
.error(function(error){
toaster.pop('error', 'Errore', error);
});
}
사용.$resource
비스듬히JS는 다음을 수행할 수 있습니다.
task.service.js
$ngTask.factory("$taskService", [
"$resource",
function ($resource) {
var taskModelUrl = 'api/task/';
return {
rest: {
taskUpload: $resource(taskModelUrl, {
id: '@id'
}, {
save: {
method: "POST",
isArray: false,
headers: {"Content-Type": undefined},
transformRequest: angular.identity
}
})
}
};
}
]);
그런 다음 모듈에서 사용합니다.
task.module.js
$ngModelTask.controller("taskController", [
"$scope",
"$taskService",
function (
$scope,
$taskService,
) {
$scope.saveTask = function (name, file) {
var newTask,
payload = new FormData();
payload.append("name", name);
payload.append("file", file);
newTask = $taskService.rest.taskUpload.save(payload);
// check if exists
}
}
POST 메서드를 사용하여 PHP 서버에서 특정 이미지 목록을 가져오고 싶다고 가정합니다.
POST 메서드의 경우 폼에 2개의 파라미터를 지정해야 합니다.이게 네가 할 일이야.
app.controller('gallery-item', function ($scope, $http) {
var url = 'service.php';
var data = new FormData();
data.append("function", 'getImageList');
data.append('dir', 'all');
$http.post(url, data, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function (response) {
// This function handles success
console.log('angular:', response);
}, function (response) {
// this function handles error
});
});
시스템에서 테스트해 봤는데 작동해요.
언급URL : https://stackoverflow.com/questions/37039852/send-formdata-with-other-field-in-angularjs
'programing' 카테고리의 다른 글
Oracle 관리 드라이버는 비동기/대기 기능을 올바르게 사용할 수 있습니까? (0) | 2023.03.02 |
---|---|
django-rest-model serializer 필드를 필수화하는 방법 (0) | 2023.03.02 |
Java 9에서 클래스 및 리소스 로드 (0) | 2023.03.02 |
Cordova + Angularjs + 디바이스 지원 (0) | 2023.03.02 |
리피터 필드에 의한 ACF 쿼리 투고가 비어 있지 않음 (0) | 2023.03.02 |