Я пытаюсь создать базовую страницу, которая загружает изображения на S3. У меня есть свои учетные данные и методы S3 для загрузки, выполняющейся на порту 8080 в Springboot, и интерфейс, работающий в Angular на порту 4200. Я могу сделать запрос POST в Postman на http://localhost:8080/storage/uploadFile, который успешно загружает изображениена мое ведро S3. Но когда я пытаюсь сделать то же самое через Angular / мое приложение, я получаю 404. Вот мой код:
Angular:
```import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component ({
selector: 'upload-images',
templateUrl: './upload-images.html',
styleUrls: ['./upload-images.css']
})
export class UploadImagesComponent {
selectedFile: File = null;
constructor(private http: HttpClient) {}
onFileSelected(event) {
this.selectedFile = <File>event.target.files[0];
}
onUpload() {
const formData = new FormData();
formData.append('image', this.selectedFile, this.selectedFile.name);
this.http.post('http://localhost:4200/storage/uploadFile', formData)
.subscribe(res => {
console.log(res);
});
}
}```
Springboot:
```package inno.garage.june19.bucket;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
@Service
public class AmazonClient {
private AmazonS3 s3client;
@Value("${amazonProperties.endpointUrl}")
private String endpointUrl;
@Value("${amazonProperties.bucketName}")
private String bucketName;
@Value("${amazonProperties.accessKey}")
private String accessKey;
@Value("${amazonProperties.secretKey}")
private String secretKey;
@PostConstruct
private void initializeAmazon() {
AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
this.s3client = new AmazonS3Client(credentials);
}
public String uploadFile(MultipartFile multipartFile) {
String fileUrl = "";
try {
File file = convertMultiPartToFile(multipartFile);
String fileName = generateFileName(multipartFile);
fileUrl = endpointUrl + "/" + bucketName + "/" + fileName;
uploadFileTos3bucket(fileName, file);
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
return fileUrl;
}
private File convertMultiPartToFile(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
private String generateFileName(MultipartFile multiPart) {
return new Date().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_");
}
private void uploadFileTos3bucket(String fileName, File file) {
s3client.putObject(new PutObjectRequest(bucketName, fileName, file)
.withCannedAcl(CannedAccessControlList.PublicRead));
}
public String deleteFileFromS3Bucket(String fileUrl) {
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
s3client.deleteObject(new DeleteObjectRequest(bucketName, fileName));
return "Successfully deleted";
}
}
```
Java Controller:
```package inno.garage.june19.bucket;
import inno.garage.june19.bucket.AmazonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/storage")
public class BucketController {
private AmazonClient amazonClient;
@Autowired
BucketController(AmazonClient amazonClient) {
this.amazonClient = amazonClient;
}
@PostMapping("/uploadFile")
public String uploadFile(@RequestPart(value = "file") MultipartFile file) {
return this.amazonClient.uploadFile(file);
}
@DeleteMapping("/deleteFile")
public String deleteFile(@RequestPart(value = "url") String fileUrl) {
return this.amazonClient.deleteFileFromS3Bucket(fileUrl);
}
}```