Я пытаюсь создать проект на Angular и Java, где я загружаю файл из интерфейса внешнего интерфейса в базу данных MySQL через серверную часть, встроенную в весеннюю загрузку.
Когда я загружаю файл из почтальона, он работает.
Когда я загружаю его из внешнего интерфейса, я получаю следующую ошибку:
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
Возможно, я неправильно вижу некоторые свойства во внешнем интерфейсе.
Вот код службы angular, откуда я загружаю файл:
@Injectable({
providedIn: 'root'
})
export class PostFileServiceService {
constructor(private http: HttpClient) { }
public postFile(name: string, size: any, type: any): Observable{
const body = JSON.stringify({name, size, type});
const Options = {
headers: new HttpHeaders({
'content-type':'multipart/form-data', 'boundary':'----WebKitFormBoundaryG8vpVejPYc8E16By'
})
}
const url = `http://localhost:8080/api/v1/file/uploa ... ype=${type}`;
return this.http.post(url, body, Options);
}
}
Я попытался добавить параметры составных границ, следуя тому, что было сказано здесь: https://www.baeldung.com/spring-avoid-n ... -was-found
но боюсь, что я написал неправильно.
Вот код из класса контроллера в Java, где я управляю вызовами на серверную часть:
@RestController
@RequestMapping(path="api/v1/file")
@CrossOrigin(origins = "http://localhost:4200")
public class filecontroller {
@Autowired
private final FileSystemStorageService filesService;
public filecontroller(FileSystemStorageService filesService) {
this.filesService = filesService;
}
@PostMapping("/upload")
public ResponseEntity uploadFiles(@RequestParam MultipartFile file){
String message = "";
try{
filesService.store(file);
message = "File Uploaded successfully: "+file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new responseMessage(message));
}catch (Exception e){
message = "Could not upload the file: "+file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new responseMessage(message));
}
}
@GetMapping("/files")
public ResponseEntity getListFiles(){
List files = filesService.getAllFiles().map(dbFile->{
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/files/").path(dbFile.getId()).toUriString();
return new fileResponse(dbFile.getFileName(), dbFile.getFileSize().length, dbFile.getType(), fileDownloadUri);
}).collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.OK).body(files);
}
@GetMapping("/files/{id}")
public ResponseEntity getFile(@PathVariable String id){
fileToUpload file = filesService.getFile(id);
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFileName()+"\"").body(file.getFileSize());
}
}
Где я делаю что-то не так?
Если вам нужен другой фрагмент кода, спросите меня.
Компонент HTML:
Где я делаю что-то не так?
Если вам нужен другой фрагмент кода, спросите меня.
Компонент HTML:
Name
Go back
{{username}}, Upload a file here!
See all the files uploaded by {{username}}
Upload a file
X
Upload
File uploaded: {{name}}
компонент js:
constructor(private route: Router, private files: PostFileServiceService) { }
public main(){
this.username = localStorage.getItem('user_name');
}
public onChangeFile(event: any){
this.file = event.target.files[0];
if(this.file){
this.name = this.file.name;
this.size = this.file.size;
this.type = this.file.type;
this.userName = this.username;
this.nameOfficial = this.name;
if(this.nameOfficial.includes(" ")){
this.nameConcat = this.nameOfficial.split(" ").join("");
}
}else if(this.file==null){
return
}
}
public onSubmit(){
this.requestSub = this.files.postFile(this.nameConcat ? this.nameConcat : this.nameOfficial, this.size, this.type).subscribe((resp)=>{
if(resp==null){
this.subscribed = true;
this.toCongrats('fileSuccessfull');
}
})
}
//other methods
Подробнее здесь: https://stackoverflow.com/questions/790 ... va-angular
Запрос был отклонен, поскольку не найдена составная граница (java/angular) ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Запрос был отклонен, поскольку не найдена составная граница (java/angular)
Anonymous » » в форуме JAVA - 0 Ответы
- 11 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Запрос был отклонен, поскольку не найдена составная граница (java/angular)
Anonymous » » в форуме JAVA - 0 Ответы
- 15 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Запрос был отклонен, поскольку в Springboot не найдена составная граница.
Anonymous » » в форуме JAVA - 0 Ответы
- 37 Просмотры
-
Последнее сообщение Anonymous
-