Я хотел загрузить изображение в Spring Boot Back End.Я думаю, что-то не так в запросе POST.Я думаю, что файл, который я отправляю с внешнего интерфейса, не подходит для внутреннего.Но возникает ошибка
core.js:1673 ERROR TypeError: Cannot read property 'length' of undefined
at http.js:108
at Array.forEach (<anonymous>)
at HttpHeaders.lazyInit (http.js:102)
at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.init (http.js:166)
at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.forEach (http.js:235)
at Observable._subscribe (http.js:1445)
at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:42)
at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:28)
at subscribeTo.js:21
at subscribeToResult (subscribeToResult.js:11)
Вот может App.Component.ts Файл
import { Component } from '@angular/core';
import { HttpClient} from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
selectedFile:File = null;
constructor(private http: HttpClient){}
onFileSelected(event){
this.selectedFile=<File>event.target.files[0];
}
onUpload(){
const fd = new FormData();
fd.append("file", this.selectedFile);
this.http.post('http://localhost:8080/doc/upload',fd,{
headers: {
'Content-Type': undefined
}
})
.subscribe(res => {
console.log(res);
});
}
}
, и это мой App.component.html
<h1>File Upload</h1>
<input type="button" (click)="onUpload()">
<input type="file" (change)="onFileSelected($event)">
<br>
При загрузке Spring
Контроллер Класс
import com.hendisantika.entity.Document;
import com.hendisantika.service.DocumentService;
import com.hendisantika.service.ResponseMetadata;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Lis
@Controller
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value = "/doc")
public class DocumentController {
private static final Logger LOG = Logger.getLogger(DocumentController.class);
@Autowired
DocumentService documentService;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
ResponseMetadata handleFileUpload(@RequestParam(value = "file") MultipartFile file) throws IOException {
return documentService.save(file);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public HttpEntity<byte[]> getDocument(@PathVariable Long id) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<byte[]>(documentService.getDocumentFile(id), httpHeaders, HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody
List<Document> getDocument() {
return documentService.findAll();
}
}
это класс DocumentService
package com.hendisantika.service;
import com.hendisantika.entity.Document;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
public interface DocumentService {
ResponseMetadata save(MultipartFile multipartFile) throws IOException;
byte[] getDocumentFile(Long id);
List<Document> findAll();
}
Вот класс DocumentSeviceImp
package com.hendisantika.service;
import com.hendisantika.dao.DocumentDao;
import com.hendisantika.entity.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@Service
public class DocumentServiceImpl implements DocumentService {
@Autowired
private DocumentDao documentDao;
@Override
public ResponseMetadata save(MultipartFile file) throws IOException {
Document doc = new Document();
doc.setDocName(file.getOriginalFilename());
doc.setFile(file.getBytes());
documentDao.save(doc);
ResponseMetadata metadata = new ResponseMetadata();
metadata.setMessage("success");
metadata.setStatus(200);
return metadata;
}
@Override
public byte[] getDocumentFile(Long id) {
return documentDao.findOne(id).getFile();
}
@Override
public List<Document> findAll() {
return (List<Document>) documentDao.findAll();
}
}
Вот класс ResponseMetaData
public class ResponseMetadata {
private int status;
private String message;
private Object data;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}