fix: fix can't upload non-png(like jpg) image bug (#530)

This commit is contained in:
Ryao 2022-08-05 00:42:45 +08:00 committed by GitHub
parent 1b92c06349
commit 2de3f85ead
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 9 additions and 10 deletions

View File

@ -274,6 +274,7 @@ func (c *ApiController) AddTopic() {
// @Title UploadTopicPic
// @Description upload topic picture
// @Param pic formData string true "the picture base64 code"
// @Param type formData string true "the picture type"
// @Success 200 {object} _controllers.Response The Response object
// @router /upload-topic-pic [post]
// @Tag Topic API
@ -284,18 +285,13 @@ func (c *ApiController) UploadTopicPic() {
memberId := c.GetSessionUsername()
fileBase64 := c.Ctx.Request.Form.Get("pic")
fileType := c.Ctx.Request.Form.Get("type")
index := strings.Index(fileBase64, ",")
if index < 0 || fileBase64[0:index] != "data:image/png;base64" {
resp := Response{Status: "error", Msg: "File encoding error"}
c.Data["json"] = resp
c.ServeJSON()
return
}
fileBytes, _ := base64.StdEncoding.DecodeString(fileBase64[index+1:])
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
fileUrl, _ := service.UploadFileToStorage(memberId, "topicPic", "UploadTopicPic", fmt.Sprintf("casnode/topicPic/%s/%s.%s", memberId, timestamp, "png"), fileBytes)
fileUrl, _ := service.UploadFileToStorage(memberId, "topicPic", "UploadTopicPic", fmt.Sprintf("casnode/topicPic/%s/%s.%s", memberId, timestamp, fileType), fileBytes)
resp := Response{Status: "ok", Msg: timestamp + ".png", Data: fileUrl}
resp := Response{Status: "ok", Msg: timestamp + "." + fileType, Data: fileUrl}
c.Data["json"] = resp
c.ServeJSON()
}

View File

@ -58,9 +58,10 @@ export function getFileNum() {
}).then((res) => res.json());
}
export function uploadTopicPic(base64) {
export function uploadTopicPic(base64, filetype) {
let formData = new FormData();
formData.append("pic", base64);
formData.append("type", filetype);
return fetch(`${Setting.ServerUrl}/api/upload-topic-pic`, {
method: "POST",
credentials: "include",

View File

@ -55,9 +55,11 @@ export function uploadMdFile(addMsg) {
return;
}
let fileType = Setting.getFileType(file.name);
let reader = new FileReader();
reader.onload = (e) => {
FileBackend.uploadTopicPic(e.target.result).then((res) => {
FileBackend.uploadTopicPic(e.target.result, fileType.ext).then((res) => {
if (res.status === "ok") {
this.uploadStatus = true;
this.onFileUploadResponse(res.msg, encodeURI(res.data));