简体   繁体   English

为什么我可以通过 Postman 将图像上传到我的 S3 存储桶,但不能通过 Node.js 上传图像?

[英]Why can I upload an image to my S3 bucket through Postman, but not through Node.js?

I'm trying to create a basic page that uploads images to S3.我正在尝试创建一个将图像上传到 S3 的基本页面。 I have my S3 credentials and methods for the upload running on port 8080 in Springboot and the front end running in Angular on port 4200. I'm able to make a POST request in Postman to http://localhost:8080/storage/uploadFile which successfully uploads an image to my S3 bucket. I have my S3 credentials and methods for the upload running on port 8080 in Springboot and the front end running in Angular on port 4200. I'm able to make a POST request in Postman to http://localhost:8080/storage/uploadFile它成功地将图像上传到我的 S3 存储桶。 But when I try to do the same through Angular/my application, I get a 404. Here's my code:但是当我尝试通过 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);
    }
}```

You are call wrong API Endpoint here您在这里调用了错误的 API 端点

onUpload() {
    const formData = new FormData();
    formData.append('image', this.selectedFile, this.selectedFile.name);
    this.http.post('http://localhost:8080/storage/uploadFile', formData)
    .subscribe(res => {
        console.log(res);
    });
}

You are calling http://localhost:4200 not http://localhost:8080你打电话给http://localhost:4200而不是http://localhost:8080

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么上传到 s3 存储桶失败,Node.js 无法写入图像数据? - Why does upload to s3 bucket fail with Node.js fail to write image data? 将图像上传到s3存储桶节点js - upload image to s3 bucket node js Node.js 和 Amazon S3:如何遍历存储桶中的所有文件? - Node.js & Amazon S3: How to iterate through all files in a bucket? 直接下载存储在S3 bucket中的文件到React客户端,而不是通过Node.js服务器 - Download file stored in S3 bucket directly to React client, instead of passing through Node.js server 将图像从 node.js 上传到 s3 存储桶 - Uploading image to s3 bucket from node.js 使用Node将映像上传到AWS S3存储桶。 JS - Upload image to AWS S3 bucket using Node. JS 将图像上传到 s3 存储桶 - 反应本机和 node.js - Upload image to s3 bucket - react native and node js 如果我为 static 网站托管配置了一个 s3 存储桶,那么我可以通过 API 将资产上传到它吗? - If I configure a s3 bucket for static website hosting, then can I upload assets to it through API? 当我尝试向 S3 存储桶 (Node.js) 发送内容时,AWS 缺少凭证 - AWS Missing credentials when I try send something to my S3 Bucket (Node.js) 如何使用Node.js获取Amazon S3存储桶的总大小? - How can I get the total size of an Amazon S3 bucket using Node.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM