Javascript 使用formGroup上载文件时出现问题
我正在使用angular制作一个包含一些信息(姓名、电子邮件、密码和头像)的注册表。后端我使用NodeJS和MongoDB来存储信息。关于后端,我已经编写了注册API OK。我在邮递员身上测试过,它对后端有用 但在angular客户机中,当我从注册表表单输入信息时,出现了错误,我使用formData将输入表单发送到后端API 我正在使用formGroup发送我的usersystem对象,包括(姓名、角色、电子邮件、密码和化身) 这是我的html文件Javascript 使用formGroup上载文件时出现问题,javascript,node.js,angular,httpclient,Javascript,Node.js,Angular,Httpclient,我正在使用angular制作一个包含一些信息(姓名、电子邮件、密码和头像)的注册表。后端我使用NodeJS和MongoDB来存储信息。关于后端,我已经编写了注册API OK。我在邮递员身上测试过,它对后端有用 但在angular客户机中,当我从注册表表单输入信息时,出现了错误,我使用formData将输入表单发送到后端API 我正在使用formGroup发送我的usersystem对象,包括(姓名、角色、电子邮件、密码和化身) 这是我的html文件 <div class="common-f
<div class="common-form float_left ">
<form [formGroup]="dialogRegisterUserSysForm" >
<div class="field_wrapper box FlowupLabels">
<label class="label">NAME</label>
<div class="field fl_wrap pad-top-0">
<input type="text" name="name" formControlName="name" maxlength="255" placeholder="Enter user system name" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
<div class="clr"></div>
</div>
<div class="field_wrapper box FlowupLabels">
<label class="label">PASSWORD</label>
<div class="field fl_wrap pad-top-0">
<input type="password" id="illness-name" class="input-big hc_name fl_input ui-autocomplete-input" name="password" formControlName="password" maxlength="255" placeholder="Please enter a password" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
<div class="error_field" id="testResultsErrors"></div> <div class="clr"></div>
</div>
<div class="field_wrapper box FlowupLabels">
<label class="label">EMAIL</label>
<div class="field fl_wrap pad-top-0">
<input type="text" id="illness-name" class="input-big hc_name fl_input ui-autocomplete-input" name="email" formControlName="email" maxlength="255" placeholder="Enter an email." autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
<div class="error_field" id="testResultsErrors"></div> <div class="clr"></div>
</div>
<div>
<label>Upload Avatar</label>
<input (change)="onFileSelect($event.target)" type="file" formControlName="avatar" class="form-control">
</div>
<div class="save-cancel-btngrp-wrap">
<div class="cancel-link switchToViewMode" style="float: right">
<a (click)="matDialogRef.close(dialogRegisterUserSysForm)" class="switchToViewMode btn flat">CANCEL</a>
</div>
<div *ngIf="action =='new'" class="cancel-link switchToViewMode" style="float: right">
<a (click)="matDialogRef.close(['save',dialogRegisterUserSysForm])" class="switchToViewMode btn flat">SAVE</a>
</div>
</div>
</form>
</div>
下面是我的ts文件
import { FormBuilder, FormGroup } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
import { UserSysService } from '../usersys.service';
import { UserSysModel } from '../usersys.model';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector : 'usersys-form-dialog',
templateUrl : './usersys-form.component.html',
styleUrls : ['./usersys.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class UserSysFormDialogComponent
{
action: string;
userSys: UserSysModel; // Medical report model
dialogRegisterUserSysForm: FormGroup;
dialogTitle: string;
/**
* Constructor
*
* @param {MatDialogRef<MedicalReportFormDialogComponent>} matDialogRef
* @param _data
* @param {FormBuilder} _formBuilder
*/
constructor(
// private _mrReportService: HealthMedicalReportService,
public matDialogRef: MatDialogRef<UserSysFormDialogComponent>,
@Inject(MAT_DIALOG_DATA) private _data: any,
private _formBuilder: FormBuilder
)
{
// this.dialogTitle = 'Add New Medical Report';
// set default here
this.action = this._data.action;
if(this.action === 'edit'){
this.dialogTitle = 'Edit User System';
this.userSys = _data.userSys;
}else{
this.dialogTitle = 'Register new User System';
this.userSys = new UserSysModel({});
}
this.dialogRegisterUserSysForm = this.createUserSystemDialogForm();
}
onFileSelect(input) {
var fInput = input.files[0];
var fileName = fInput.name;
alert(fileName);
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = (e: any) => {
alert("Result: " + e.target.result);
this.userSys.avatar = e.target.result;
// reader.readAsDataURL(input.files[0]);
}
// this.userSys.avatar = e.target.result;
reader.readAsDataURL(input.files[0]);
}
}
/**
* Create UserSystem form
*
* @returns {FormGroup}
*/
createUserSystemDialogForm(): FormGroup
{
return this._formBuilder.group({
email : [this.userSys.email],
password : [this.userSys.password],
name : [this.userSys.name],
avatar : [this.userSys.avatar]
});
}
}
从'@angular/forms'导入{FormBuilder,FormGroup};
从“@angular/material”导入{MAT_DIALOG_DATA,MatDialogRef};
从“../usersys.service”导入{UserSysService};
从“../usersys.model”导入{UserSysModel};
从'rxjs'导入{Subject};
从“rxjs/operators”导入{takeUntil};
@组成部分({
选择器:“usersys表单对话框”,
templateUrl:'./usersys form.component.html',
样式URL:['./usersys.component.scss'],
封装:视图封装。无
})
导出类UserSysFormDialogComponent
{
动作:字符串;
userSys:UserSysModel;//医疗报告模型
dialogRegisterUserSysForm:FormGroup;
对话框标题:字符串;
/**
*建造师
*
*@param{MatDialogRef}MatDialogRef
*@param\u数据
*@param{FormBuilder}\u FormBuilder
*/
建造师(
//私人报告服务:HealthMedicalReportService,
公共matDialogRef:matDialogRef,
@注入(MAT_DIALOG_DATA)私有数据:任意,
私有_formBuilder:formBuilder
)
{
//this.dialogTitle='添加新的医疗报告';
//在此处设置默认值
this.action=this.\u data.action;
如果(this.action==='edit'){
this.dialogTitle='编辑用户系统';
this.userSys=\u data.userSys;
}否则{
this.dialogTitle='注册新用户系统';
this.userSys=新的UserSysModel({});
}
this.dialogRegisterUserSysForm=this.createUserSystemDialogForm();
}
onFileSelect(输入){
var fInput=input.files[0];
var fileName=fInput.name;
警报(文件名);
if(input.files&&input.files[0]){
var reader=new FileReader();
reader.onload=(e:any)=>{
警报(“结果:+e.target.Result”);
this.userSys.avatar=e.target.result;
//reader.readAsDataURL(input.files[0]);
}
//this.userSys.avatar=e.target.result;
reader.readAsDataURL(input.files[0]);
}
}
/**
*创建用户系统表单
*
*@returns{FormGroup}
*/
createUserSystemDialogForm():FormGroup
{
返回此。\u formBuilder.group({
电子邮件:[this.userSys.email],
密码:[this.userSys.password],
名称:[this.userSys.name],
阿凡达:[this.userSys.avatar]
});
}
}
以下是我的注册表格的图像:
但是我得到了错误“fakepath”,我无法将此表单发布到服务器
我认为我的英语不好,所以可能是我的解释很难理解。
非常感谢您
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script>
window.onload = function () {
document.getElementById("uploadfile").disabled = true;
document.getElementById("excelData").disabled = false;
};
document.addEventListener('keydown', function (e) {
if (e.which == 116) {
window.onbeforeunload = function () {
window.onbeforeunload = null;
$(".se-pre-con").fadeIn("slow");
}
}
}, false);
$(document).ready(function () {
$(".se-pre-con").fadeOut("slow");;
});
function LoadPreloder() {
$(".se-pre-con").fadeIn("slow");;
}
function UnloadPreloder() {
$(".se-pre-con").fadeOut("slow");;
}
function enableDisable() {
var FileSelectedValue = null;
var ClassSelected = 0;
FileSelectedValue = document.getElementById("excelData").value;
ClassSelected = document.getElementById("SelectedClass").value;
//alert(ClassSelected);
if (document.getElementById("excelData").files.length) {
// alert("File is Selected !!");
document.getElementById("uploadfile").disabled = false;
}
else if (!document.getElementById("excelData").files.length) {
//alert("No File Selected !");
document.getElementById("uploadfile").disabled = true;
}
}
</script>
@section AngularScripts{
<script type="text/javascript">
var schoolStuff = angular.module("schoolStuff", ['lr.upload']);
schoolStuff.controller("downloadDataformateController", ['$scope', 'upload', '$http', function ($scope, upload, $http) {
$http.get('@Url.Action("GetStandardDivisionList", "Collection")')
.then(function (response) {
$scope.Standard_Mapping_Division = response.data;
// $scope.Standard_Mapping_DivisionId = $scope.Standard_Mapping_Division[0].Standard_Mapping_DivisionId;
$scope.dataType = [
{ "dataTypeId": "1", "dataTypeValue": "Student" },
{ "dataTypeId": "2", "dataTypeValue": "Teacher" }
];
$scope.dataTypeId = $scope.dataType[0].dataTypeId;
$scope.showdragdrop = null;
});
$scope.uploadExcel = function () {
LoadPreloder();
if ($scope.dataFile != undefined) {
upload({
url: '@Url.Action("PostExcelStudent", "ManageExcelData")',
method: 'POST',
data: {
standard_mapping_divisionId: $scope.Standard_Mapping_DivisionId,
typeId: $scope.dataTypeId,
dataFile: $scope.dataFile
}
}).then(function (response) {
alert(response.data.Message);
$scope.UploadedStudentData = response.data.studentsdata;
UnloadPreloder();
});
}
}
$scope.changeme = function () {
//alert($scope.showdragdrop);
//enableDisable();
$scope.showdragdrop = 1;
// alert($scope.showdragdrop);
}
$scope.uploadStudentData = function () {
LoadPreloder($scope.UploadedStudentData);
console.log()
$http({
url: '@Url.Action("UploadStudentData", "ManageExcelData")',
method: 'POST',
data: {
standard_mapping_divisionId: $scope.Standard_Mapping_DivisionId,
studentData: $scope.UploadedStudentData
}
}).then(function (response) {
$scope.InsertedStudentData = response.data.studentsdata;
if (($scope.InsertedStudentData).length != 0) {
UnloadPreloder();
$scope.UploadedStudentDataNull = null;
$('html, body').animate({ scrollTop: $('#InseertedStudentRecord').offset().top }, 'slow');
//console.log(response);
//alert(response.data.Message);
//alert(response.data.teachersdata);
//alert(response.data.Success);
$scope.InsertedStudentData = response.data.studentsdata;
if (response.data.Success != 0) {
if (($scope.InsertedStudentData).length != 0) {
UnloadPreloder();
$scope.UploadedStudentDataNull = null;
$('html, body').animate({ scrollTop: $('#InseertedStudentRecord').offset().top }, 'fast');
}
else if (($scope.InsertedStudentData).length == 0) {
$scope.UploadedTeacherDataNull = 0;
UnloadPreloder();
// alert($scope.UploadedTeacherDataNull);
}
}
else if (response.data.Success == 0) {
alert(response.data.Message);
UnloadPreloder();
}
}
else if (($scope.InsertedStudentData).length == 0) {
$scope.UploadedStudentDataNull = 0;
UnloadPreloder();
// alert($scope.UploadedTeacherDataNull);
}
UnloadPreloder();
});
}
}]).directive('uploadFile', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var file_uploaded = $parse(attrs.uploadFile);
element.bind('change', function () {
scope.$apply(function () {
file_uploaded.assign(scope, element[0].files[0]);
});
});
}
};
}]);
</script>
}
window.onload=函数(){
document.getElementById(“uploadfile”).disabled=true;
document.getElementById(“excelData”).disabled=false;
};
文档.添加的事件列表器('keydown',函数(e){
如果(e.which==116){
window.onbeforeunload=函数(){
window.onbeforeunload=null;
美元(“.se pre con”).fadeIn(“慢”);
}
}
},假);
$(文档).ready(函数(){
美元(“.se pre con”)。淡出(“慢”);;
});
函数loadpreoder(){
美元(“.se pre con”).fadeIn(“慢”);;
}
函数UnloadPreloder(){
美元(“.se pre con”)。淡出(“慢”);;
}
函数enableDisable(){
var FileSelectedValue=null;
var ClassSelected=0;
FileSelectedValue=document.getElementById(“excelData”).value;
ClassSelected=document.getElementById(“SelectedClass”).value;
//警报(已选择类别);
if(document.getElementById(“excelData”).files.length){
//警报(“已选择文件!!”;
document.getElementById(“uploadfile”).disabled=false;
}
else if(!document.getElementById(“excelData”).files.length){
//警报(“未选择任何文件!”);
document.getElementById(“uploadfile”).disabled=true;
}
}
@节角脚本{
var schoolStuff=angular.module(“schoolStuff”,['lr.upload']);
controller(“downloadDataformateController”[“$scope”,“upload”,“$http”,函数($scope,upload,$http){
$http.get('@Url.Action(“GetStandardDivisionList”、“Collection”))
.然后(功能(响应){
$scope.Standard_Mapping_Division=response.data;
//$scope.Standard_Mapping_Division id=$scope.Standard_Mapping_Division[0]。Standard_Mapping_Division id;
$scope.dataType=[
{“dataTypeId”:“1”,“dataTypeValue”:“Student”},
{“dataTypeId”:“2”,“dataTypeValue”:“教师”}
];
$scope.dataTypeId=$scope.dataType[0]。dataTypeId;
$scope.showdragdrop=null;
});
$scope.uploadExcel=函数(){
loadpreoder();
如果($scope.dataFile!=未定义){
上传({
url:'@url.Action(“PostExcelStudent”、“ManageExcelData”),
方法:“POST”,
数据:{
标准映射\u分区ID:$scope.standard\u映射_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script>
window.onload = function () {
document.getElementById("uploadfile").disabled = true;
document.getElementById("excelData").disabled = false;
};
document.addEventListener('keydown', function (e) {
if (e.which == 116) {
window.onbeforeunload = function () {
window.onbeforeunload = null;
$(".se-pre-con").fadeIn("slow");
}
}
}, false);
$(document).ready(function () {
$(".se-pre-con").fadeOut("slow");;
});
function LoadPreloder() {
$(".se-pre-con").fadeIn("slow");;
}
function UnloadPreloder() {
$(".se-pre-con").fadeOut("slow");;
}
function enableDisable() {
var FileSelectedValue = null;
var ClassSelected = 0;
FileSelectedValue = document.getElementById("excelData").value;
ClassSelected = document.getElementById("SelectedClass").value;
//alert(ClassSelected);
if (document.getElementById("excelData").files.length) {
// alert("File is Selected !!");
document.getElementById("uploadfile").disabled = false;
}
else if (!document.getElementById("excelData").files.length) {
//alert("No File Selected !");
document.getElementById("uploadfile").disabled = true;
}
}
</script>
@section AngularScripts{
<script type="text/javascript">
var schoolStuff = angular.module("schoolStuff", ['lr.upload']);
schoolStuff.controller("downloadDataformateController", ['$scope', 'upload', '$http', function ($scope, upload, $http) {
$http.get('@Url.Action("GetStandardDivisionList", "Collection")')
.then(function (response) {
$scope.Standard_Mapping_Division = response.data;
// $scope.Standard_Mapping_DivisionId = $scope.Standard_Mapping_Division[0].Standard_Mapping_DivisionId;
$scope.dataType = [
{ "dataTypeId": "1", "dataTypeValue": "Student" },
{ "dataTypeId": "2", "dataTypeValue": "Teacher" }
];
$scope.dataTypeId = $scope.dataType[0].dataTypeId;
$scope.showdragdrop = null;
});
$scope.uploadExcel = function () {
LoadPreloder();
if ($scope.dataFile != undefined) {
upload({
url: '@Url.Action("PostExcelStudent", "ManageExcelData")',
method: 'POST',
data: {
standard_mapping_divisionId: $scope.Standard_Mapping_DivisionId,
typeId: $scope.dataTypeId,
dataFile: $scope.dataFile
}
}).then(function (response) {
alert(response.data.Message);
$scope.UploadedStudentData = response.data.studentsdata;
UnloadPreloder();
});
}
}
$scope.changeme = function () {
//alert($scope.showdragdrop);
//enableDisable();
$scope.showdragdrop = 1;
// alert($scope.showdragdrop);
}
$scope.uploadStudentData = function () {
LoadPreloder($scope.UploadedStudentData);
console.log()
$http({
url: '@Url.Action("UploadStudentData", "ManageExcelData")',
method: 'POST',
data: {
standard_mapping_divisionId: $scope.Standard_Mapping_DivisionId,
studentData: $scope.UploadedStudentData
}
}).then(function (response) {
$scope.InsertedStudentData = response.data.studentsdata;
if (($scope.InsertedStudentData).length != 0) {
UnloadPreloder();
$scope.UploadedStudentDataNull = null;
$('html, body').animate({ scrollTop: $('#InseertedStudentRecord').offset().top }, 'slow');
//console.log(response);
//alert(response.data.Message);
//alert(response.data.teachersdata);
//alert(response.data.Success);
$scope.InsertedStudentData = response.data.studentsdata;
if (response.data.Success != 0) {
if (($scope.InsertedStudentData).length != 0) {
UnloadPreloder();
$scope.UploadedStudentDataNull = null;
$('html, body').animate({ scrollTop: $('#InseertedStudentRecord').offset().top }, 'fast');
}
else if (($scope.InsertedStudentData).length == 0) {
$scope.UploadedTeacherDataNull = 0;
UnloadPreloder();
// alert($scope.UploadedTeacherDataNull);
}
}
else if (response.data.Success == 0) {
alert(response.data.Message);
UnloadPreloder();
}
}
else if (($scope.InsertedStudentData).length == 0) {
$scope.UploadedStudentDataNull = 0;
UnloadPreloder();
// alert($scope.UploadedTeacherDataNull);
}
UnloadPreloder();
});
}
}]).directive('uploadFile', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var file_uploaded = $parse(attrs.uploadFile);
element.bind('change', function () {
scope.$apply(function () {
file_uploaded.assign(scope, element[0].files[0]);
});
});
}
};
}]);
</script>
}
this.formGroup.patchValue({
avatar: reader.result
});
// Mark dirty
this.cdRef.markForCheck();