feat(image): 优化图片上传和预览功能

- 修改图片上传接口,支持用户 ID 和 Markdown ID 参数
- 实现在线预览功能,支持多种文件类型
- 优化图片插入到 Markdown 编辑器的逻辑
- 更新数据库配置和连接字符串
This commit is contained in:
2025-08-01 17:21:16 +08:00
parent 7a7247a851
commit 2bb265d23f
13 changed files with 91 additions and 30 deletions

View File

@@ -8,10 +8,15 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
@@ -20,19 +25,21 @@ import java.util.List;
@RequestMapping("/api/images") @RequestMapping("/api/images")
public class ImageController { public class ImageController {
@Value("${file.upload-dir}")
private String rootPath;
@Autowired @Autowired
private ImageService imageService; private ImageService imageService;
@Operation(summary = "上传图片") @Operation(summary = "上传图片")
@Parameters({
@Parameter(name = "file", description = "图片文件", required = true)
})
@PostMapping @PostMapping
public R<Image> uploadImage( public R<Image> uploadImage(
@RequestParam("file") MultipartFile file) { @RequestParam("file") MultipartFile file,
@RequestParam(value = "userId", required = false) Long userId,
@RequestParam(value = "markdownId", required = false) Long markdownId) {
try { try {
Image image = imageService.uploadImage(file); Image image = imageService.uploadImage(file, userId, markdownId);
return R.success(image); return R.success(image);
} catch (IOException e) { } catch (IOException e) {
return R.fail(); return R.fail();
@@ -50,6 +57,33 @@ public class ImageController {
} }
} }
/**
* 在线预览图片、视频、音频、pdf 等浏览器可直接识别的类型)
*/
@GetMapping("/preview/{url}")
@Operation(summary = "在线预览", description = "浏览器直接打开文件流")
public void preview(@PathVariable String url, HttpServletResponse resp) throws IOException {
if (url == null) {
resp.setStatus(404);
R.fail("文件不存在");
}
File file = new File(rootPath + File.separator + url);
if (!file.exists()) {
resp.setStatus(404);
R.fail("文件不存在");
}
String contentTypeFromFileExtension = getContentTypeFromFileExtension(url);
// 设置正确的 MIME
resp.setContentType(contentTypeFromFileExtension);
// 设置文件长度,支持断点续传
resp.setContentLengthLong(file.length());
// 写出文件流
try (FileInputStream in = new FileInputStream(file)) {
StreamUtils.copy(in, resp.getOutputStream());
}
}
@Operation(summary = "根据url删除图片") @Operation(summary = "根据url删除图片")
@PostMapping("/deleteByUrl") @PostMapping("/deleteByUrl")
public R<Void> deleteImageByUrl(@RequestParam String url) { public R<Void> deleteImageByUrl(@RequestParam String url) {
@@ -73,4 +107,34 @@ public class ImageController {
} }
/**
* 根据文件扩展名获取内容类型
* @param fileName 文件名
* @return 对应的MIME类型
*/
private String getContentTypeFromFileExtension(String fileName) {
if (fileName == null || fileName.lastIndexOf('.') == -1) {
return "application/octet-stream";
}
String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
switch (extension) {
case "jpg":
case "jpeg":
return "image/jpeg";
case "png":
return "image/png";
case "gif":
return "image/gif";
case "bmp":
return "image/bmp";
case "webp":
return "image/webp";
case "svg":
return "image/svg+xml";
default:
return "application/octet-stream";
}
}
} }

View File

@@ -14,7 +14,7 @@ public interface ImageService extends IService<Image> {
* @return 上传的图片对象 * @return 上传的图片对象
* @throws IOException 文件操作异常 * @throws IOException 文件操作异常
*/ */
Image uploadImage(MultipartFile file) throws IOException; Image uploadImage(MultipartFile file, Long userId, Long markdownId) throws IOException;
/** /**
* 删除图片 * 删除图片

View File

@@ -33,7 +33,7 @@ public class ImageServiceImpl
private ImageMapper imageMapper; private ImageMapper imageMapper;
@Override @Override
public Image uploadImage( MultipartFile file) throws IOException { public Image uploadImage( MultipartFile file, Long userId, Long markdownId) throws IOException {
// 创建上传目录 // 创建上传目录
Path uploadPath = Paths.get(uploadDir); Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) { if (!Files.exists(uploadPath)) {
@@ -53,10 +53,11 @@ public class ImageServiceImpl
Image image = new Image(); Image image = new Image();
image.setOriginalName(originalFilename); image.setOriginalName(originalFilename);
image.setStoredName(storedName); image.setStoredName(storedName);
image.setUrl("/uploads/" + storedName); image.setUrl("/api/images/preview/" + storedName);
image.setSize(file.getSize()); image.setSize(file.getSize());
image.setContentType(file.getContentType()); image.setContentType(file.getContentType());
image.setCreatedAt(new Date()); image.setCreatedAt(new Date());
image.setMarkdownId(markdownId);
this.save(image); this.save(image);
return image; return image;

View File

@@ -1,8 +1,8 @@
spring: spring:
datasource: datasource:
driver-class-name: org.sqlite.JDBC driver-class-name: org.sqlite.JDBC
url: jdbc:sqlite:C:\it\houtaigunli\biji\mydatabase.db # url: jdbc:sqlite:C:\it\houtaigunli\biji\mydatabase.db
# url: jdbc:sqlite:C:\KAIFA\2\mydatabase.db url: jdbc:sqlite:C:\KAIFA\2\mydatabase.db
jpa: jpa:
hibernate: hibernate:
ddl-auto: none ddl-auto: none

View File

@@ -29,10 +29,12 @@ export const deleteImages = (list) => {
}) })
} }
// 上传图片 // 上传图片
export const uploadImage = (file) => { export const uploadImage = (file, userId, markdownId) => {
const formData = new FormData() const formData = new FormData()
if (file) formData.append('file', file) if (file) formData.append('file', file)
return axiosApi.post('/api/images?markdownId', formData, { if (userId) formData.append('userId', userId)
if (markdownId) formData.append('markdownId', markdownId)
return axiosApi.post('/api/images', formData, {
headers: { headers: {
'Content-Type': 'multipart/form-data' 'Content-Type': 'multipart/form-data'
} }

View File

@@ -527,14 +527,16 @@ const editNote = async (file) => {
// 图片上传 // 图片上传
const handleImageUpload=async (files) => { const handleImageUpload=async (files) => {
const promise = await uploadImage(files); const promise = await uploadImage(files[0]);
if (promise.code !== 200) { if (promise.code !== 200) {
ElMessage.error(promise.msg); ElMessage.error(promise.msg);
return; return;
} }
const url = promise.data; const url = promise.data.url;
imageUrls.value.push(url); // 修正IP地址并正确拼接
vditor.value.insertValue(`![${files[0].name}](${url})`); const baseUrl = "http://127.0.0.1:8084";
imageUrls.value.push(baseUrl + url);
vditor.value.insertValue(`![${files[0].name}](${baseUrl + url})`);
} }
const debouncedSave = (value) => { const debouncedSave = (value) => {

View File

@@ -21,10 +21,10 @@
<script> <script>
import MarkdownEditor from '@/components/MarkdownEditor.vue'; import MarkdownEditor from '@/components/MarkdownEditor.vue';
import VMdPreview from '@kangc/v-md-editor/lib/preview';
import { ref } from 'vue'; import { ref } from 'vue';
import { ElMessage } from 'element-plus'; import { ElMessage } from 'element-plus';
import axios from 'axios'; import axios from 'axios';
import {uploadImage} from "@/api/CommonApi.js";
export default { export default {
name: 'MarkdownEditor', name: 'MarkdownEditor',
@@ -85,19 +85,8 @@ export default {
const handleImageUpload = async (event, insertImage, files) => { const handleImageUpload = async (event, insertImage, files) => {
const file = files[0]; const file = files[0];
const formData = new FormData();
formData.append('file', file);
formData.append('userId', userId.value);
formData.append('markdownId', currentFileId.value);
try { try {
const API_BASE_URL = 'http://localhost:8083'; const response = await uploadImage(file, userId.value, currentFileId.value);
const response = await axios.post(`${API_BASE_URL}/api/images`, formData, {
withCredentials: true,
headers: {
'Content-Type': 'multipart/form-data'
}
});
// 插入图片到编辑器 // 插入图片到编辑器
insertImage({ insertImage({

View File

@@ -11,3 +11,6 @@ vite+vue3.js怎么支持markdown文件的上传预览、编辑、创建呢
MarkdownFile(id=325279554144964608, userId=1, title=测试, fileName=测试, content=userId=1&title=%E6%B5%8B%E8%AF%95&fileName=%E6%B5%8B%E8%AF%95&content=%E6%B5%8B%E8%AF%95, createdAt=2025-06-16T22:24:49.110387, updatedAt=2025-06-16T22:24:49.110387) MarkdownFile(id=325279554144964608, userId=1, title=测试, fileName=测试, content=userId=1&title=%E6%B5%8B%E8%AF%95&fileName=%E6%B5%8B%E8%AF%95&content=%E6%B5%8B%E8%AF%95, createdAt=2025-06-16T22:24:49.110387, updatedAt=2025-06-16T22:24:49.110387)
https://segmentfault.com/blog/chengxy-nds

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB