Golang中上传文件及其他字段问题如何解决

Golang中上传文件及其他字段问题如何解决 我上传了包含其他字段(如 pname、pdescription 等)的文件,但出现了一个错误。 “http: panic serving 127.0.0.1:52987: Error 1054: Unknown column ‘pname’ in ‘field list’” 这是我的前端代码。

<div class="row">
    <div class="col-sm-3"></div>
    <div class="col-sm-6">
      <div class="form-group row">
        <div class="col-md-3">
          <label> Prodcucto name </label>
        </div>
        <div class="col-md-9">
           <input type="text" name="pname" class="form-control" />
        </div>
      </div>

      <div class="form-group row">
        <div class="col-md-3">
          <label> Prodcucto description</label>
        </div>
        <div class="col-md-9">
           <input type="text" name="pdescription" class="form-control" />
        </div>
      </div>

      <div class="form-group row">
        <div class="col-md-3">
         <label>Valorunidade</label>
        </div>
        
        <div class="col-md-9">
          <input type="text" name="cellnumber" class="form-control" />
        </div>
      </div>

      <div class="form-group row">
        <div class="col-md-3">

          <label> Producto img </label>
        </div>
        <div class="col-md-9">
         <input type="file" name="pimg" class="form-control" />
         </div>
      </div>


      <div class="form-group row">
        <div class="col-md-3">

            <label> status </label>
        </div>
        
        <div class="col-md-9">
        <select name="status" class="form-control">
            <option selected>Selecione um status</option>
            <option value="pago">Pago</option>
            <option value="parcial">Parcial</option>
            <option value="em aberto">Em Aberto</option>
        </select>
        </div>
      </div>
    
      <div class="form-group row">
        <div class="col-md-3">
          <label> Obs </label>
        </div>
        <div class="col-md-9">
          <textarea type="text" name="obs" class="form-control"></textarea><br />
        </div>
      </div>
      <button type="submit" class="btn btn-info" value="Gerar Producto">Gerar Producto</button> 
 
    </div>
  </div>
</form>

以及我的上传函数

func ProductStore(w http.ResponseWriter, r *http.Request) {

 r.ParseMultipartForm(10 << 20)
// FormFile returns the first file for the given key `myFile`
// it also returns the FileHeader so we can get the Filename,
// the Header and the size of the file
file, handler, err := r.FormFile("pimg")
if err != nil {
    fmt.Println("Error Retrieving the File")
    fmt.Println(err)
    return
}
defer file.Close()
fmt.Printf("Uploaded File: %+v\n", handler.Filename)
fmt.Printf("File Size: %+v\n", handler.Size)
fmt.Printf("MIME Header: %+v\n", handler.Header)

// Create a temporary file within our temp-images directory that follows
// a particular naming pattern
tempFile, err := ioutil.TempFile("product", "*.png")
fmt.Println(tempFile)
if err != nil {
    fmt.Println(err)
}
defer tempFile.Close()

// read all of the contents of our uploaded file into a
// byte array
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
    fmt.Println(err)
}
// write this byte array to our temporary file
tempFile.Write(fileBytes)
// return that we have successfully uploaded our file!
fmt.Fprintf(w, "Successfully Uploaded File\n")
//Open database connection
db := dbConn()

// Check the request form METHOD
if r.Method == "POST" {

	// Get the values from Form
	pname := r.FormValue("pname")
	pdescription := r.FormValue("pdescription")
	valorunidade := r.FormValue("valorunidade")
	pdatafabi := r.FormValue("pdatafabi")
	pimg := "product.png"
	status := r.FormValue("status")
	obs := r.FormValue("obs")
	// Prepare a SQL INSERT and check for errors
	insForm, err := db.Prepare("INSERT INTO clientes(pname, pdescription, valorunidade, pdatafabi, pimg, status, obs) VALUES(?,?,?,?,?,?,?)")
	if err != nil {
		panic(err.Error())
	}

	// Execute the prepared SQL, getting the form fields
	insForm.Exec(pname, pdescription, valorunidade, pdatafabi, pimg, status, obs)

	// Show on console the action
	log.Println("INSERT: pname " +pname+ " | pdescription " +pdescription+ " | valorunidade " +valorunidade+ " | pdatafabi " +pdatafabi+ " |pimg " +pimg+ " |status " +status+ " |obs " +obs)
}

// Close database connection
defer db.Close()

// Redirect to HOME
http.Redirect(w, r, "/product", 301)
}

问题是什么?


更多关于Golang中上传文件及其他字段问题如何解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中上传文件及其他字段问题如何解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


这个错误是数据库层面的错误,不是Go代码本身的语法错误。错误信息表明你的SQL语句中引用了不存在的数据库列。

在你的Go代码中,SQL插入语句使用了以下列名:

insForm, err := db.Prepare("INSERT INTO clientes(pname, pdescription, valorunidade, pdatafabi, pimg, status, obs) VALUES(?,?,?,?,?,?,?)")

但是错误信息显示数据库表中没有pname这个列。有以下几个可能的问题:

  1. 数据库表结构不匹配:你的clientes表可能没有定义pname这个列
  2. 列名拼写错误:可能是pnamepdescription等列名在数据库中不存在或者拼写不同

检查你的数据库表结构,确保clientes表包含以下列:

  • pname
  • pdescription
  • valorunidade
  • pdatafabi
  • pimg
  • status
  • obs

另外,你的前端表单中有cellnumber字段,但后端代码中获取的是valorunidade,这可能是另一个问题:

// 前端是 name="cellnumber"
<input type="text" name="cellnumber" class="form-control" />

// 后端获取的是 valorunidade
valorunidade := r.FormValue("valorunidade")

修正后的代码应该这样获取字段值:

func ProductStore(w http.ResponseWriter, r *http.Request) {
    // 先解析表单
    err := r.ParseMultipartForm(10 << 20)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    
    // 处理文件上传
    file, handler, err := r.FormFile("pimg")
    if err != nil {
        fmt.Fprintf(w, "Error Retrieving the File: %v", err)
        return
    }
    defer file.Close()
    
    // 保存文件
    tempFile, err := ioutil.TempFile("product", "*.png")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer tempFile.Close()
    
    fileBytes, err := ioutil.ReadAll(file)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    tempFile.Write(fileBytes)
    
    // 获取表单字段 - 修正字段名
    pname := r.FormValue("pname")
    pdescription := r.FormValue("pdescription")
    valorunidade := r.FormValue("cellnumber") // 注意这里改为cellnumber
    pdatafabi := r.FormValue("pdatafabi")
    pimg := handler.Filename // 使用实际文件名
    status := r.FormValue("status")
    obs := r.FormValue("obs")
    
    // 数据库连接
    db := dbConn()
    defer db.Close()
    
    // 准备SQL语句 - 确保列名与数据库表结构匹配
    insForm, err := db.Prepare("INSERT INTO clientes(pname, pdescription, valorunidade, pdatafabi, pimg, status, obs) VALUES(?,?,?,?,?,?,?)")
    if err != nil {
        panic(err.Error())
    }
    defer insForm.Close()
    
    // 执行插入
    _, err = insForm.Exec(pname, pdescription, valorunidade, pdatafabi, pimg, status, obs)
    if err != nil {
        panic(err.Error())
    }
    
    http.Redirect(w, r, "/product", http.StatusSeeOther)
}

首先检查你的数据库表结构,使用以下SQL查看clientes表的列定义:

DESCRIBE clientes;
-- 或
SHOW COLUMNS FROM clientes;

根据查询结果调整你的SQL语句中的列名,确保它们完全匹配。

回到顶部