Я пытаюсь загрузить изображения в хранилище superbase с помощью Spring, но каждый раз, когда я запускаю конечную точку, я получаю эту ошибку. У меня в хранилище есть только 1 ведро под названием «slike», и в нем нет подпапок. Я попытался добавить в это ведро все доступные политики, но, похоже, это не сработало. Я использую ключ service_role.
POST http://localhost:8080/posts/create
HTTP/1.1 500
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Mon, 30 Dec 2024 00:36:22 GMT
Connection: close
{
"timestamp": "2024-12-30T00:36:22.381+00:00",
"status": 500,
"error": "Internal Server Error",
"message": "Error uploading to Supabase: 400 Bad Request from PUT https://pccmxztqfmfucdbgcydr.supabase.c ... images.jpg",
"path": "/posts/create"
}
Response file saved.
> 2024-12-30T013622.500.json
Response code: 500; Time: 24630ms (24 s 630 ms); Content length: 255 bytes (255 B)
@PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity createPost(@RequestParam String userEmail,
@RequestParam String textContent,
@RequestPart(value = "file", required = false) MultipartFile file) {
// 1. Get the user
User user = userRepository.findByEmail(userEmail)
.orElseThrow(() -> new RuntimeException("User not found with email: " + userEmail));
// 2. Only Partner can create a post
if (user.getUserType() != UserType.PARTNER) {
return ResponseEntity.badRequest().body("Only a Partner can create posts.");
}
// 3. If file is present, upload to Supabase
String imageUrl = null;
if (file != null && !file.isEmpty()) {
// Build a unique path in the bucket:
// e.g., "public/posts/" + System.currentTimeMillis() + "-" + file.getOriginalFilename()
String pathInBucket = file.getOriginalFilename();
imageUrl = supabaseStorageService.uploadFile(file, "slike", pathInBucket);
}
// 4. Create the Post in local DB (text + optional imageUrl)
Post newPost = postService.createPost(user, textContent, imageUrl);
// 5. Return the newly created Post
return ResponseEntity.ok(newPost);
}
package hr.fer.sportconnect.db;
import hr.fer.sportconnect.db.SupabaseStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.client.WebClient;
@Service
public class SupabaseStorageServiceImpl implements SupabaseStorageService {
// These come from application.properties or environment variables
@Value("${supabase.project.url}") // e.g. "https://xxxxxx.supabase.co"
private String supabaseUrl;
@Value("${supabase.key}") // Your service_role or anon key
private String supabaseKey;
@Override
public String uploadFile(MultipartFile file, String bucketName, String pathInBucket) {
try {
// 1. Convert to byte[]
byte[] fileBytes = file.getBytes();
// 2. Build the full upload endpoint:
// "https://.supabase.co/storage/v1/object/{bucketName}/{pathInBucket}"
String uploadUrl = supabaseUrl + "/storage/v1/object/"
+ bucketName + "/" + pathInBucket;
// 3. Perform POST or PUT request
WebClient webClient = WebClient.builder()
.baseUrl(uploadUrl)
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + supabaseKey)
.build();
webClient.put()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.bodyValue(fileBytes)
.retrieve()
.bodyToMono(String.class) // The response body
.block(); // Execute synchronously
// 4. Build the public URL (assuming your bucket is public):
// e.g., "https://xxxxxx.supabase.co/storage/v1/o ... thInBucket}"
// If it's private, you'd generate a signed URL separately.
String publicUrl = supabaseUrl + "/storage/v1/object/public/"
+ bucketName + "/" + pathInBucket;
return publicUrl;
} catch (Exception e) {
throw new RuntimeException("Error uploading to Supabase: " + e.getMessage(), e);
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... ing-spring
Возникли проблемы с загрузкой изображений в хранилище Supabase с помощью Spring. ⇐ JAVA
Программисты JAVA общаются здесь
1735522369
Anonymous
Я пытаюсь загрузить изображения в хранилище superbase с помощью Spring, но каждый раз, когда я запускаю конечную точку, я получаю эту ошибку. У меня в хранилище есть только 1 ведро под названием «slike», и в нем нет подпапок. Я попытался добавить в это ведро все доступные политики, но, похоже, это не сработало. Я использую ключ service_role.
POST http://localhost:8080/posts/create
HTTP/1.1 500
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Mon, 30 Dec 2024 00:36:22 GMT
Connection: close
{
"timestamp": "2024-12-30T00:36:22.381+00:00",
"status": 500,
"error": "Internal Server Error",
"message": "Error uploading to Supabase: 400 Bad Request from PUT https://pccmxztqfmfucdbgcydr.supabase.co/storage/v1/object/slike/images.jpg",
"path": "/posts/create"
}
Response file saved.
> 2024-12-30T013622.500.json
Response code: 500; Time: 24630ms (24 s 630 ms); Content length: 255 bytes (255 B)
@PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity createPost(@RequestParam String userEmail,
@RequestParam String textContent,
@RequestPart(value = "file", required = false) MultipartFile file) {
// 1. Get the user
User user = userRepository.findByEmail(userEmail)
.orElseThrow(() -> new RuntimeException("User not found with email: " + userEmail));
// 2. Only Partner can create a post
if (user.getUserType() != UserType.PARTNER) {
return ResponseEntity.badRequest().body("Only a Partner can create posts.");
}
// 3. If file is present, upload to Supabase
String imageUrl = null;
if (file != null && !file.isEmpty()) {
// Build a unique path in the bucket:
// e.g., "public/posts/" + System.currentTimeMillis() + "-" + file.getOriginalFilename()
String pathInBucket = file.getOriginalFilename();
imageUrl = supabaseStorageService.uploadFile(file, "slike", pathInBucket);
}
// 4. Create the Post in local DB (text + optional imageUrl)
Post newPost = postService.createPost(user, textContent, imageUrl);
// 5. Return the newly created Post
return ResponseEntity.ok(newPost);
}
package hr.fer.sportconnect.db;
import hr.fer.sportconnect.db.SupabaseStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.client.WebClient;
@Service
public class SupabaseStorageServiceImpl implements SupabaseStorageService {
// These come from application.properties or environment variables
@Value("${supabase.project.url}") // e.g. "https://xxxxxx.supabase.co"
private String supabaseUrl;
@Value("${supabase.key}") // Your service_role or anon key
private String supabaseKey;
@Override
public String uploadFile(MultipartFile file, String bucketName, String pathInBucket) {
try {
// 1. Convert to byte[]
byte[] fileBytes = file.getBytes();
// 2. Build the full upload endpoint:
// "https://.supabase.co/storage/v1/object/{bucketName}/{pathInBucket}"
String uploadUrl = supabaseUrl + "/storage/v1/object/"
+ bucketName + "/" + pathInBucket;
// 3. Perform POST or PUT request
WebClient webClient = WebClient.builder()
.baseUrl(uploadUrl)
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + supabaseKey)
.build();
webClient.put()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.bodyValue(fileBytes)
.retrieve()
.bodyToMono(String.class) // The response body
.block(); // Execute synchronously
// 4. Build the public URL (assuming your bucket is public):
// e.g., "https://xxxxxx.supabase.co/storage/v1/object/public/{bucketName}/{pathInBucket}"
// If it's private, you'd generate a signed URL separately.
String publicUrl = supabaseUrl + "/storage/v1/object/public/"
+ bucketName + "/" + pathInBucket;
return publicUrl;
} catch (Exception e) {
throw new RuntimeException("Error uploading to Supabase: " + e.getMessage(), e);
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79316629/having-problems-uploading-images-to-supabase-storage-using-spring[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия