golang+gin使用arco design upload组件实现文件上传

前言

用到的所有东西有:golang、gin、typescript、axios、arco design

后端用的是golang+gin搭建服务端,前端在使用arco design的upload组件的默认上传时感觉有点难受,用axios写了个自定义上传

后端

func UploadStudentFile(ctx *gin.Context) {

 fileName, err := url.QueryUnescape(ctx.Request.Header.Get("X-FileName"))

if err != nil {

 ctx.JSON(http.StatusOK, ErrorResponse(serializer.CodeParamErr, "上传失败", err))

return

}

if fileExt := strings.ToLower(path.Ext(fileName)); fileExt != ".zip" {

 ctx.JSON(http.StatusOK, ErrorResponse(serializer.CodeParamErr, "文件类型校验失败", nil))

return

}

if strings.Contains(fileName, "..") || strings.Contains(fileName, "/") {

 ctx.JSON(http.StatusOK, ErrorResponse(serializer.CodeNoPermissionErr, "非法上传", nil))

return

}

 outputFile, _ := os.Create("./upload/" + fileName)

defer outputFile.Close()

 body := ctx.Request.Body

defer body.Close()

 _, err = io.Copy(outputFile, body)

if err != nil {

 ctx.JSON(http.StatusOK, ErrorResponse(serializer.CodeParamErr, "上传失败", err))

return

}

 ctx.JSON(http.StatusOK, OKResponse("上传成功", nil))

}

前端

<Upload

 accept={'.zip'} //允许上传的文件后缀

 name="file"

 limit={1}

 autoUpload={true} //选了文件后直接执行上传操作

 listType="text"

// 上传前弹确认上传选框

 beforeUpload={(file) => {

return new Promise((resolve, reject) => {

 Modal.confirm({

 title: '确认上传',

 content: 确认上传 ${file.name},

 onConfirm: () => resolve(true),

 onCancel: () => reject('cancel'),

});

});

}}

// 自定义上传器

 customRequest={(options) => {

const { onProgress, onError, onSuccess, file } = options;

const header = {

'Content-Type': 'application/octet-stream',

'X-FileName': encodeURIComponent(file.name),

};

 axios

 .create({

// 上传百分比,实现上传进度

 onUploadProgress: function (ProgressEvent) {

const load = ProgressEvent.loaded;

const total = ProgressEvent.total;

const progress = (load / total) * 100;

console.log(progress);

onProgress(progress);

},

})

 .post('file/upload', file, {

 headers: header,

})

 .then((res) => {

if (res.status === 200) {

onSuccess(res);

} else {

onError(res.data.msg);

}

});

}}

 >

原创文章,如需转载请注明出处

LICENSED UNDER CC BY-NC-SA 4.0
Comment