Я получаю внутреннюю служебную ошибку, когда пытаюсь загрузить изображение с помощью приложения angular. Я использовал загрузку ng2-файла. Не могли бы вы помочь мне исправить код?
Photo-editor.Component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Photo } from 'src/app/_models/Photo';
import { FileUploader } from 'ng2-file-upload';
import { environment } from 'src/environments/environment';
import { AuthService } from 'src/app/_services/auth.service';
@Component({
selector: 'app-photo-editor',
templateUrl: './photo-editor.component.html',
styleUrls: ['./photo-editor.component.css']
})
export class PhotoEditorComponent implements OnInit {
@Input() photos: Photo[];
uploader: FileUploader;
hasBaseDropZoneOver = false;
baseUrl = environment.apiUrl;
constructor(private authService: AuthService) { }
ngOnInit() {
this.initializeUploader();
}
fileOverBase(e: any): void {
this.hasBaseDropZoneOver = e;
}
initializeUploader()
{
this.uploader = new FileUploader({
url: this.baseUrl + 'users/' + this.authService.decodedToken.nameid + '/photos',
authToken: 'Brearer ' + localStorage.getItem('token'),
isHTML5: true,
allowedFileType: ['image'],
removeAfterUpload: true,
autoUpload: false,
maxFileSize: 10 * 1024 * 1024
});
this.uploader.onAfterAddingFile = (file) =>
{
file.withCredentials = false;
};
}
}
photo-editor.component. Html
<div class="row">
<div class="col-sm-2" *ngFor="let photo of photos">
<img src="{{photo.url}}" class="img-thumbnail p-1" alt="">
<div class="text-center">
<button type="button" class="btn btn-sm">Main</button>
<button type="button" class="btn btn-sm btn-danger"><i class="fa fa-trash-o"></i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<h3>Select files</h3>
<div ng2FileDrop
[ngClass]="{'nv-file-over': hasBaseDropZoneOver}"
(fileOver)="fileOverBase($event)"
[uploader]="uploader"
class="well my-drop-zone">
Base drop zone
</div>
Multiple
<input type="file" ng2FileSelect [uploader]="uploader" multiple /><br/>
Single
<input type="file" ng2FileSelect [uploader]="uploader" />
</div>
<div class="col-md-9" style="margin-bottom: 40px">
<h3>Upload queue</h3>
<p>Queue length: {{ uploader?.queue?.length }}</p>
<table class="table">
<thead>
<tr>
<th width="50%">Name</th>
<th>Size</th>
<th>Progress</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of uploader.queue">
<td><strong>{{ item?.file?.name }}</strong></td>
<td *ngIf="uploader.options.isHTML5" nowrap>{{ item?.file?.size/1024/1024 | number:'.2' }} MB</td>
<td *ngIf="uploader.options.isHTML5">
<div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': item.progress + '%' }"></div>
</div>
</td>
<td class="text-center">
<span *ngIf="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
<span *ngIf="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
<span *ngIf="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
</td>
<td nowrap>
<button type="button" class="btn btn-success btn-xs"
(click)="item.upload()" [disabled]="item.isReady || item.isUploading || item.isSuccess">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
<button type="button" class="btn btn-warning btn-xs"
(click)="item.cancel()" [disabled]="!item.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel
</button>
<button type="button" class="btn btn-danger btn-xs"
(click)="item.remove()">
<span class="glyphicon glyphicon-trash"></span> Remove
</button>
</td>
</tr>
</tbody>
</table>
<div>
<div>
Queue progress:
<div class="progress" >
<div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': uploader.progress + '%' }"></div>
</div>
</div>
<button type="button" class="btn btn-success btn-s"
(click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
<span class="glyphicon glyphicon-upload"></span> Upload all
</button>
<button type="button" class="btn btn-warning btn-s"
(click)="uploader.cancelAll()" [disabled]="!uploader.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel all
</button>
<button type="button" class="btn btn-danger btn-s"
(click)="uploader.clearQueue()" [disabled]="!uploader.queue.length">
<span class="glyphicon glyphicon-trash"></span> Remove all
</button>
</div>
</div>
</div>
<br><br>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Response</div>
<div class="panel-body">
<!-- {{ response }} -->
</div>
</div>
</div>
</div>
app. module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import { AppComponent } from './app.component';
import { BsDropdownModule} from 'ngx-bootstrap/dropdown';
import {TabsModule} from 'ngx-bootstrap/tabs';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {RouterModule} from '@angular/router';
import {JwtModule} from '@auth0/angular-jwt';
import { FileUploadModule } from 'ng2-file-upload';
import { NgxGalleryModule } from 'ngx-gallery-9';
import { NavComponent } from './nav/nav.component';
import {FormsModule} from '@angular/forms';
import {AuthService} from './_services/auth.service';
import { HomeComponent } from './home/home.component';
import { RegisterComponent } from './register/register.component';
import {ErrorInterceptorProvider} from './_services/error.interceptor';
import { MemberListComponent } from './members/member-list/member-list.component';
import { ListsComponent } from './lists/lists.component';
import { MessagesComponent } from './messages/messages.component';
import {appRoutes} from './routes';
import {UserService} from './_services/user.service';
import {MemberCardComponent} from './members/member-card/member-card.component';
import {MemberDetailComponent} from './members/member-detail/member-detail.component';
import {MemberDetailResolver} from './_resolver/member-detail.resolver';
import { MemberListResolver } from './_resolver/member-list.resolver';
import {MemberEditComponent} from './members/member-edit/member-edit.component';
import {MemberEditResolver} from './_resolver/member-edit.resolver';
import {PreventUnsavedChanges} from './_guards/prevent-unsaved-change.guard';
import {PhotoEditorComponent} from './members/photo-editor/photo-editor.component';
// tslint:disable-next-line: typedef
export function tokenGetter()
{
return localStorage.getItem('token');
}
@NgModule({
declarations: [
AppComponent,
NavComponent,
HomeComponent,
RegisterComponent,
MemberListComponent,
ListsComponent,
MessagesComponent,
MemberCardComponent,
MemberDetailComponent,
MemberEditComponent,
PhotoEditorComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
NgxGalleryModule,
FileUploadModule,
BrowserAnimationsModule,
TabsModule.forRoot(),
BsDropdownModule.forRoot(),
RouterModule.forRoot(appRoutes),
JwtModule.forRoot({
config: {
tokenGetter : tokenGetter,
allowedDomains : ['localhost:5000'],
disallowedRoutes: ['localhost:5000/api/auth']
}
})
],
providers: [
AuthService,
ErrorInterceptorProvider,
UserService,
MemberDetailResolver,
MemberListResolver,
MemberEditResolver,
PreventUnsavedChanges
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Ошибка:
Не удалось определить порт https для перенаправления. сбой: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware [1]
Произошло необработанное исключение при выполнении запроса.
System.NullReferenceException: ссылка на объект не установлена на экземпляр объекта.
в MyApp.api.Controllers.PhotosController.AddPhotoForUser (Int32 userId, PhotoForCreationDto photoForCreationDto) в C: \ MyApp \ myapp.api \ Controllers \ PhotosController.cs: строка 68 в Microsoft.AspNetCore. Mvc .Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute (сопоставитель IActionResultTypeMapper, исполнитель ObjectMethodExecutor, контроллер объекта, аргументы Object []) в Microsoft.AspNetCore. Mvc .Infrastructure.ControllerActionInvoker.g__Awaited | 12_0 (вызывающий ControllerActionInvoker, ValueTask`1 actionResultValueTask) в Microsoft.AspNetCore. Mvc .Infrastructure.ControllerActionTask, Task_ActionInvoker.g__0 , Scope scope, Object state, Boolean isCompleted) в Microsoft.AspNetCore. Mvc .Infrastructure.ControllerActionInvoker.Rethrow (ActionExecutedContextSealed context) в Microsoft.AspNetCore. Mvc .Infrastructure.ControllerActionInvoker.Next (State & next, Object & next, состояние, логическое значение & isCompleted) в Microsoft.AspNetCore. Mvc .Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsyn c () --- Конец трассировки стека из предыдущего места, где было сгенерировано исключение --- в Microsoft.AspNetCore. Mvc .Infrastructure.ResourceInvoker.g__Awaited | 24_0 (вызывающий ResourceInvoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) в Microsoft.AspNetCore. Mvc .Infrastructure.ResourceInvoker.Rethrow (ResourceExecutedContextSealed context) в Microsoft.AspNetCore. Mvc .Infrastructure. ResourceInvoker.Next (State & next, Scope & scope, Object & state, Boolean & isCompleted) в Microsoft.AspNetCore. Mvc .Infrastructure.ResourceInvoker.InvokeFilterPipelineAsyn c () --- Конец трассировки стека из предыдущего места, где было сгенерировано исключение - - в Microsoft.AspNetCore. Mvc .Infrastructure.ResourceInvoker.g__Awaited | 17_0 (вызывающий ResourceInvoker, задача задачи, область действия IDisposable) в Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask | 6_0 (конечная точка r Endpoint, задача equestTask, регистратор ILogger) в Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke (контекст HttpContext) в Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke (контекст HttpContext) в Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleContext * 10 * контекст HttpContext * 10 *