Загрузка изображения в форме - PullRequest
0 голосов
/ 25 мая 2019

У меня угловая форма с текстовыми полями, и я хочу добавить опцию загрузки изображения в той же форме. Я застрял с последним.

Угловая форма содержит HTML-тег для загрузки файла. После загрузки файла имя загруженного файла отображается в поле ввода.

<!--blog.html-->
<!--form to create new blog--> 

    <form #blogForm="ngForm" (ngSubmit)="Save(blogForm);">
                    <div class="form-group">
                      <label>Blog Title</label>
                      <input type="text" class="form-control input-text" maxlength="45" name="title" ngModel #blogtitle="ngModel"  required placeholder="Blog Title">
                      <span class="required" *ngIf="blogtitle.errors?.required && (blogtitle.dirty||blogtitle.touched||blogtitle.untouched)">*required</span>
                    </div>
                    <div class="form-group">
                      <label>Blog </label>
                      <textarea class="textarea form-control" maxlength="150" name="summary" [(ngModel)]="summary">
                        Blog</textarea>
                    </div>
                    <div class="form-group">
                      <label>Blog Desc</label>
                      <textarea class="textarea form-control" name="description" ngModel #blogdescription="ngModel" required>Blog Description</textarea>
                      <span  class="required" *ngIf="blogdescription.errors?.required && (blogdescription.dirty||blogdescription.touched||blogdescription.untouched)">*required</span>
                    </div>
                    <div class="form-group">
                      <label>HashTags</label>
                      <input type="text" class="form-control input-text" name="hashtag" [(ngModel)]="hashtag" placeholder="hashtags">
                    </div>

                    <div class="form-group">
                      <div class="custom-file">
    <!--file upload -->
                        <input type="file" class="custom-file-input form-control-lg" name="file" id="customFile"
                         value="imageFile.name" (change)="handleImageFileInput($event)">
                        <input type="text" readonly="true"  [value]="imageFile" class="custom-file-label"  >
                        <button  type="button" (click)="upload()">Upload</button>
                      </div>
                    </div>
                    <input type="button" class="btn-default" (click)="Save(blogForm)" value="Create">
                  </form>

//blog.ts
//function to create  new blog 

    Save(blogForm: any) {

        if (blogForm.valid === true)  {
          blogForm = blogForm.value;
          blogForm.userId = this.user_id;
          blogForm.author = this.display_name;
          window.confirm('Want to Publish?');
          this.blogservice.Save(blogForm).subscribe(response => {
          window.alert('Blog published successfully');
          this.router.navigate(['/dashboard']);
          });
        }
      }

//function to display selected image in the input field


    handleImageFileInput(event) {
        const img1 =event.target.files[0];
        const img =event.target.files[0].name;
        const fileList: FileList = event.target.files;
        const fileCount = fileList.length;
        if (fileCount > 0) {
          const file = fileList.item(0);
          console.log(` image file: ${file.name}`);
          console.log(img1);

          if(img == undefined) {
           this.imageFile = 'Upload an image';
         } else {
         this.imageFile = img;
         }
      }

    }

Необходимо сохранить файл вместе с отправкой формы

1 Ответ

0 голосов
/ 25 мая 2019

Вот скрипт JavaScript, который будет считывать ваши данные из ввода и отображать их:

<input type='file' accept='image/*' onchange='openFile(event)'><br>
<img id='output'>
<script>
  var openFile = function(event) {
    var input = event.target;

    var reader = new FileReader();
    reader.onload = function(){
      var dataURL = reader.result;
      var output = document.getElementById('output');
      output.src = dataURL;
    };
    reader.readAsDataURL(input.files[0]);
  };
</script>

Он взят из документации FileReader .Благодаря этому вы сможете хранить input в любом месте и хранить путь внутри вашей коллекции MongoDB.Иначе, если вы хотите использовать угловые плагины, вот один, который может быть полезен для вас: angular-file-upload

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...