我有一个使用反应式编程的 Spring Boot CRUD。我正在使用 Azure Blob 容器来处理数据。我的阅读方法效果很好。但是我还无法测试我的上传方法,因为邮递员总是抛出错误:
400 BAD_REQUEST "Required query parameter 'file' is not present."
一开始我以为我的方法有问题,然后我将返回类型更改为 void 并将正文留空,我从 Postman 得到了相同的响应。我很确定这与 Postman 本身有关。
到目前为止,我已经:
这些都不起作用,在 Postman 中按下发送(POST)按钮后,它立即抛出相同的 400 错误。
这就是提到的方法:
// From service implementation class
@Override
public Mono<Void> uploadBlob(MultipartFile file) throws IOException {
String blobName = file.getOriginalFilename();
if (blobName == null || blobName.isEmpty()) {
return Mono.error(new IllegalArgumentException("Invalid file name"));
}
logger.info("Uploading blob: {}", blobName);
return blobContainerAsyncClient.getBlobAsyncClient(blobName)
.uploadFromFile(file.getResource().getFile().getPath(), true) // true para sobrescribir si ya existe
.then();
}
// From controller class
@PostMapping("/upload")
public Mono<ResponseEntity<Void>> uploadBlob(@RequestParam("file") MultipartFile file) throws IOException {
return azureBlobService.uploadBlob(file)
.thenReturn(ResponseEntity.ok().<Void>build());
}```
Any ideas on this are welcomed.
我尝试使用以下代码使用 Postman 将文件上传到 Azure Blob 存储。
代码:
import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController
@RequestMapping("/upload-file")
public class UploadFile {
private final BlobServiceClient blobServiceClient;
public UploadFile() {
String connectionString = "<connec_string>";
this.blobServiceClient = new BlobServiceClientBuilder().connectionString(connectionString).buildClient();
}
@PostMapping
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient("<container_name>");
String originalFileName = file.getOriginalFilename();
BlobClient blobClient = containerClient.getBlobClient(originalFileName);
blobClient.upload(file.getInputStream(), file.getSize(), true);
System.out.println("Blob uploaded successfully: " + originalFileName);
return ResponseEntity.ok("File uploaded successfully");
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(500).body("Failed to upload the file");
}
}
}
输出:
运行成功,如下图:
我使用 Postman 将文件上传到 Azure Blob 存储,如下所示。
Azure 门户:
blob 已成功上传到 Azure 门户中的 Azure 存储,如下所示。
参考: 请参阅我的 SO 线程答案 以从 Azure 存储下载 blob。