用 wails 包装web 文件上传的问题

用 wails 包装web 文件上传的问题

问题发现

wails 包装了现有的web 项目,在测试的时候发现,文件上传的时候,上传失败。看了下请求,文件传了,没问题。

难道是有鬼了!!!

启动后台,打断点继续找问题,发现后端根本没收到文件,凭空消失了吗?

寻找问题

百度感觉是解决不了啥问题,然后就在github 上找到wails ,根据问题的表现,用Ai 翻译了下,提了个issues

github.com/wailsapp/wa...

css 复制代码
Description
I used the AccessServer's handler to receive requests from the frontend, but I found that the ContentLength of the received POST request is always 0, and there is no data in the body either.

前端通过 表单上传了一个文件,但是后台无法接受文件

To Reproduce
I created a form in the frontend to upload files, but the backend is not receiving the files.

前端通过 表单上传了一个文件,但是后台无法接受文件

Expected behaviour
can upload file

能上传文件

Screenshots

问题是下午5点钟提上去的,结果 5点26的时候就得到回复,这个反馈速度还是很快的。回答的大致意思就是,这个是webview2 的一个bug ,然后给了个链接,过去看了下,确实如此

MicrosoftEdge/WebView2Feedback#2162

这个bug 已经有很久了 commented on Feb 11, 2022 ,到现在依旧没解决,有兴趣的可以点进去看下。

wails 那边回复,换种思路,用go的方式解决。

解决问题

用go 的方式解决,因为项目是最先开发的web 段,用的elementui ,上传组件是封装好的。解决方案要求要改动最小,然后就自己写了一个同名的上传组件,兼容elementui 的上传组件,在包装的这边,替换上就行了,说干就干。

go的上传逻辑如下 ,主要就是把 upload 组件的 选择文件 ,和上传文件的两个步骤,用go来实现,其他的保持不变

代码实现

1,先做下go打开文件选择框,和上传文件的逻辑

go 复制代码
// 打开选择文件对话框
func (a *App) OpenDialog() string {

	// 返回选择的文件

	options := runtime.OpenDialogOptions{
		// Filters: ,
	}

	filepath, err := runtime.OpenFileDialog(a.ctx, options)

	if err != nil {
		return "选择文件失败"
	}

	return filepath

}
go 复制代码
// 上传文件的方法,传入文件路径
func (a *App) UploadFile(upInfo UpdateInfo) UpdateResp {

	// fmt.Println("upinfo", upInfo)

	file, err := os.OpenFile(upInfo.Filename, os.O_RDONLY, 0)
	if err != nil {
		fmt.Println(err.Error() + upInfo.Filename)
		return UpdateResp{400, err.Error()}
	}

	body := new(bytes.Buffer)

	// 创建一个 `Writer` 对象,并将其写入到 `w` 中。
	w := multipart.NewWriter(body)

	// 将 `file` 对象写入到 `Writer` 中。
	// 注意,这里的 `file` 对象必须实现 `io.Reader` 接口。

	fileForm, err := w.CreateFormFile("file", upInfo.Filename)
	if err != nil {
		return UpdateResp{400, err.Error()}
	}

	_, err = io.Copy(fileForm, file)
	if err != nil {
		return UpdateResp{400, err.Error()}
	}
	// 关闭 `Writer` 对象。
	err = w.Close()
	if err != nil {
		return UpdateResp{400, err.Error()}
	}

	// 发送 `POST` 请求。
	req, err := http.NewRequest("POST", BaseUrl+upInfo.Action, body)
	if err != nil {
		return UpdateResp{400, err.Error()}
	}

	// 设置请求头。
	req.Header.Set("Content-Type", w.FormDataContentType())
	req.Header.Set("Authorization", upInfo.Header["Authorization"])

	// 发送请求。
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return UpdateResp{400, err.Error()}
	}

	// 关闭响应。
	defer resp.Body.Close()

	// 检查响应状态码。
	if resp.StatusCode != http.StatusOK {
		return UpdateResp{400, "上传文件失败"}
	}

	respBy, _ := io.ReadAll(resp.Body)

	// 返回 nil。
	return UpdateResp{200, string(respBy)}
}

2,写一个自定义的upload 组件,把UploadFile , OpenDialog 引进来,点击上传组件的时候,调用OpenDialog

vue 复制代码
<template>
  <div @click="openChoseFileDlg">
    <slot></slot>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { UploadFile,OpenDialog} from "@w/go/api/App";

export default {
  name:"ElUploadCs",
  props: {
    action: {
      type: String,
    },
    accept: {
      type: String,
    },
    beforeUpload:{
      type:Function,
      default:()=>{

      }
    },
    onSuccess:{
      type:Function,
      default:()=>{

      }
    },
    onError:{
      type:Function,
      default:()=>{

      }
    },
    onProgress:{
      type:Function,
      default:()=>{

      }
    },
  },
  data() {
    return {
      headerMsg: { Authorization: getToken() },
      filename:"",
    };
  },
  methods: {

    openChoseFileDlg(){
      OpenDialog().then(res=>{
        console.log("chose file :",res)
        if (res!=""){
          this.filename = res
          this.doUploadFile()
        }
      })
    },

    doUploadFile(){
      let params = {
        "action":this.action,
        "filename":this.filename,
        "header":this.headerMsg
      }
      console.log(params)
      this.beforeUpload()
      this.handleProgress()
      UploadFile(params).then(res=>{
          console.log(res)
          if (res.code== 200) {
            let resData = JSON.parse(res.data)
            console.log(resData)
            this.onSuccess(resData)
          }else{
            this.onError()
          }

          // this.$emit("onSuccess",resData)
      })

    },

    handleProgress() {
      if (this.utips) {
        this.dialogViable = false;
        this.fileUploadVisible = true;
      }
    },
    handleError() {
      if (this.utips) {
        this.fileUploadVisible = false;
        this.vMsg = "文件导入失败!";
        this.fileSuccessVisible = true;
      }
    },
  },
};
</script>

3,调用,引入自定义组件 ,命名为 ElUplaod,跟element-ui 里面的组件名字一样,然后在 components 中引入就可以了

javascript 复制代码
import ElUpload from "@/components/upload-cs"

components: {ElUpload },
相关推荐
不爱吃糖的程序媛3 小时前
浅谈前端架构设计与工程化
前端·前端架构设计
郝YH是人间理想5 小时前
系统架构设计师案例分析题——web篇
前端·软件工程
Evaporator Core5 小时前
深入探索:Core Web Vitals 进阶优化与新兴指标
前端·windows
初遇你时动了情5 小时前
html js 原生实现web组件、web公共组件、template模版插槽
前端·javascript·html
QQ2740287565 小时前
Soundness Gitpod 部署教程
linux·运维·服务器·前端·chrome·web3
前端小崔5 小时前
从零开始学习three.js(18):一文详解three.js中的着色器Shader
前端·javascript·学习·3d·webgl·数据可视化·着色器
哎呦你好6 小时前
HTML 表格与div深度解析区别及常见误区
前端·html
运维@小兵6 小时前
vue配置子路由,实现点击左侧菜单,内容区域显示不同的内容
前端·javascript·vue.js
koiy.cc6 小时前
记录:echarts实现tooltip的某个数据常显和恢复
前端·echarts
一只专注api接口开发的技术猿7 小时前
企业级电商数据对接:1688 商品详情 API 接口开发与优化实践
大数据·前端·爬虫