Я пытаюсь загрузить файл на свой сервер, например, сохранить путь к базе данных и файл в папку, поскольку я попытался загрузить ng-file здесь, это мой код.Функция ng-file-upload не запускает функцию
<form ng-show="divPatient" name="PatientForm" ng-submit="AddUpdatePatient()">
<table>
<tr>
<td>
<input class="form-control" type="text" readonly placeholder="Key (Automatic)" ng-model="PatientID" />
</td>
<td>
<input id="FormFocus" name="FirstName" class="form-control" type="text" placeholder="FirstName" ng-model="FirstName" ng-minlength="3" required />
</td>
<td>
<input name="LastName" class="form-control" type="text" placeholder="LastName" ng-model="LastName" ng-minlength="3" required />
</td>
<td>
<input class="form-control" type="text" placeholder="Disease" ng-model="Disease" name="Disease" ng-minlength="3" required />
</td>
<td>
<input class="form-control" type="number" placeholder="Phone No." ng-model="PhoneNo" name="PhoneNo" ng-pattern="/^[789]\d{9}$/" required />
</td>
<td>
<input type="file" ng-file-select="onFileSelect($files)" class="form-control" ng-model="PhotoURL" required />
</td>
<td colspan="2">
<input type="submit" value="save" class="btn btn-success" ng-disabled="PatientForm.PhoneNo.$dirty && PatientForm.PhoneNo.$invalid || PatientForm.LastName.$dirty && PatientForm.LastName.$invalid || PatientForm.FirstName.$dirty && PatientForm.FirstName.$invalid || PatientForm.Disease.$dirty && PatientForm.Disease.$invalid" />
<input type="button" value="cancel" class="btn btn-primary" ng-click="CancelForm()" />
</td>
</tr>
<tr>
<td></td>
<td><span class="eror-text" ng-show="PatientForm.FirstName.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.LastName.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.Disease.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.PhoneNo.$error.pattern">Invalid phone no</span></td>
</tr>
</table>
</form>
вот мой Угловая код
var app = angular.module('StudentApp', ['ngFileUpload']);
app.controller("StudentCtrl", function ($scope, angularService) {
$scope.selectedFile = [];
//On file Select
$scope.onFileSelect = function ($files) {
//This function not running at all ??
alert("where I'm i ???");
//$scope.selectedFile = $files;
//alert($files);
}
$scope.AddUpdatePatient = function() {
var file = $scope.selectedFile[0];
alert($scope.PhotoURL);
var Patient = {
FirstName: $scope.FirstName,
LastName: $scope.LastName,
Disease: $scope.Disease,
PhoneNo: $scope.PhoneNo
};
var getAction = $scope.Action;
if (getAction == "Update") {
Patient.PatientID = $scope.PatientID;
var getData = angularService.UpdatePatient(Patient,file);
getData.then(function (msg) {
GetAllPatients();
alert(msg.data);
$scope.divPatient = false;
}, function() {
alert('Error in updating record');
});
} else {
var getData = angularService.AddPatient(Patient);
getData.then(function (msg) {
GetAllPatients();
alert(msg.data);
$scope.divPatient = false;
}, function() {
alert('Error in adding record');
});
}
}
Мои зависимости
bundles.Add(new ScriptBundle("~/bundles/CustomPlugins").Include(
"~/Scripts/ng-file-upload-shim.min.js",
"~/scripts/angular.min.js",
"~/Scripts/ng-file-upload.min.js"));
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/CustomPlugins")
Где я пойти не так, пожалуйста скажите мне, как я загрузить файл в ActionResult с помощью angularjs, спасибо
ok я попробовал onchange
onchange="angular.element(this).scope().selectFileforUpload(this.files)"
, но я не могу отправить файл в мой результат действия, его показ меня нулевой,
$scope.selectFileforUpload = function (files) {
$scope.selectedFile = files;
}
$scope.AddUpdatePatient = function() {
var file = $scope.selectedFile[0];
var Patient = {
FirstName: $scope.FirstName,
LastName: $scope.LastName,
Disease: $scope.Disease,
PhoneNo: $scope.PhoneNo
};
var getData = angularService.AddPatient(Patient,filee);
getData.then(function (msg) {
GetAllPatients();
alert(msg.data);
$scope.divPatient = false;
}, function() {
alert('Error in adding record');
});
}
вот мой код услуги
this.AddPatient = function (patient, file) {
// this showing me file object thats fine
alert("in services" + filee);
// i think something wrong here we shouldn't or can't send the file to actionresult like this
var response = $http({
method: "post",
url: "AddPatient",
data: JSON.stringify(patient),
dataType: "json",
file : file
});
return response;
}
драмы последнего моего результате действия
public string AddPatient(Patient patient,HttpPostedFileBase file)
{
// I'm getting patient data that is fine, but file is showing me null
}
что-то не так с моим методом обслуживания ??? или вы знаете, как отправить форму вместе с файлами в actionresult или любой метод в контроллере mvc, я слышал, как некоторые плееры делают это с помощью «новой FormData», но я не знаю этого, но я готов изучить его или использовать он, если это решает мою проблему
Есть вы попробовали отладку, чтобы подтвердить, что функция действительно не вызывается? Если у вас есть Chrome, откройте консоль, перейдите в «Источники», выберите свой js-файл, найдите функцию 'onFileSelect' и положите на него' break'. Затем попробуйте загрузить файл и посмотреть, выполняет ли функция –
. В соответствии с nme-file-upload readme вы должны использовать 'ngf-change = fileSelected ($ file, $ event)' вместо вашего 'ng-file-selected'. Вы отлаживались с помощью консоли, чтобы проверить, есть ли какие-либо ошибки? Потому что, если вы используете ng -..., который не распознается, он может полностью разбить углы – Guinn