Angular: Как отправить файл как часть данных формы, которые при загрузке сопоставляются с классом домена? - PullRequest
0 голосов
/ 21 января 2020

У меня есть форма html, как указано ниже

 <form #basicForm = "ngForm" (ngSubmit) = "onClickSubmit(basicForm.value)" enctype="multipart/form-data" class="form-horizontal">
     <input type="file" id="file-input" name="fileInput" ngModel>
     <button type="submit"> Submit</button>
 </form>

, а метод onClickSubmit -

 onClickSubmit(data) {
    console.log(data.fileInput);
    this.http.post("http://localhost:8080/basicForm", data).subscribe( (ob)=>(console.log("subscribe method called")));
  }

Но это только регистрирует поддельный путь в консоли браузера, как C:\fakepath\User.java, а не сам файл

и я не могу получить доступ к файлу со стороны сервера. Кажется, на сервер загружен только поддельный путь, а не сам файл

FormDomain java class

public class FormDomain {
 private File fileInput;

public File getFileInput() {
    return fileInput;
}

public void setFileInput(File fileInput) {
    this.fileInput = fileInput;
}

}

FormController

@CrossOrigin(origins="*")
@RestController
public class FormController {
      @PostMapping(path="/basicForm")
 public String postResponseController(
              @RequestBody FormDomain loginForm) throws IOException {

          BufferedReader br = new BufferedReader(new FileReader(loginForm.getFileInput())); 

          String st; 
          while ((st = br.readLine()) != null) { 
            System.out.println(st); 
          } 

         return "file transfer completed successfully";
     }
}

Доступ к загруженным файлам таким образом приводит к ошибке java.io.FileNotFoundException: C:\fakepath\User.java (No such file or directory). Как отправить файл как данные формы детали, которые при загрузке сопоставляются с классом домена?

1 Ответ

0 голосов
/ 21 января 2020

Вы должны написать метод изменения

 <form #basicForm = "ngForm" (ngSubmit) = "onClickSubmit(basicForm.value)" enctype="multipart/form-data" class="form-horizontal">
     <input type="file" id="file-input" name="fileInput" (change)="onFileChange($event)" ngModel>
     <button type="submit"> Submit</button>
 </form>

В файле TS,

selectedFile : any = null;
onFileChange(event){
 if (event.target.files && event.target.files.length) {
  this.pdfFile = event.target.files[0];
 }
}

при отправке на сервер

onClickSubmit(data) {
    data.fileInput = this.selectedFile ;
    console.log(data.fileInput);
    this.http.post("http://localhost:8080/basicForm", data).subscribe( (ob)=>(console.log("subscribe method called")));
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...