Spring Boot集成Cloudinary上传文档(Excel/DOCX/PDF等)后无法获取正确格式下载URL的问题求助
Spring Boot集成Cloudinary上传文档(Excel/DOCX/PDF等)后无法获取正确格式下载URL的问题求助
我在Java Spring Boot项目中使用Cloudinary上传Excel、DOCX、PDF这类文档文件时遇到了问题:上传完成后返回的URL无法让我下载到格式正确的文件——要么下载下来的文件没有后缀名,要么下载后无法正常打开查看内容。
我是通过uploadSingleFileToFolder方法来处理文件上传的,代码如下:
public String uploadSingleFileToFolder(MultipartFile file, String folderName) throws IOException, AppException { if (file.getSize() > maxFileSize) { throw new AppException("File size exceeds the maximum allowed size."); } if (!isContentTypeAllowed(file.getContentType())) { throw new AppException("Unsupported file type: " + file.getContentType()); } // Get the original filename String originalFilename = file.getOriginalFilename(); if (originalFilename == null) { throw new AppException("Invalid file name."); } // Remove the file extension for public_id String filenameWithoutExtension = originalFilename.replaceAll("\\.[^.]+$", ""); // Upload the file with the correct resource_type var options = ObjectUtils.asMap( "folder", folderName, "public_id", filenameWithoutExtension, "use_filename", true, "unique_filename", false, "resource_type", "auto" // Set resource_type to "raw" for documents ); var uploadResult = cloudinary.uploader().upload(file.getBytes(), options); return uploadResult.get("secure_url").toString(); }
比如我上传一个名为example.xlsx的Excel文件后,返回的URL是这样的:
https://res.cloudinary.com/dndoreidh/raw/upload/v1740554207/project-document/example
当我访问这个URL时,浏览器会下载一个没有后缀名的文件(比如直接叫example而不是example.xlsx),导致无法直接用Excel打开。
我目前使用的是Cloudinary的免费版,并且已经尝试了以下几种方法,但问题依然存在:
- 在上传选项中设置
resource_type为auto - 确认返回的是
secure_url而不是url - 上传前校验过文件的Content-Type是正确的
请问大家有没有什么解决思路或者方案?
备注:内容来源于stack exchange,提问作者Code-forever
相关产品推荐
相关产品推荐

