上传文件

//上传文件
func (this *ObjectController) UploadFiles() {
    url, _ := base.GetApiLink(this.Ctx.Request)
    result := base.NewApiResult(Version, url)
    this.Data["json"] = result
    fileKey := "file"
    //获取文件
    f, fh, err := this.GetFile(fileKey)
    if err != nil {
        result.GenerateErrorApiResult(fmt.Sprintf("获取文件错误,错误原因为:[ %s ]", err.Error()))
        beego.Error(result.Error.Msg)
        this.ServeJSON()
        return
    }
 
    // 建立临时处理目录
    tmpDir := filepath.Join("plugin/template/upload")
    base.Mkdirs([]string{tmpDir})
    beego.Debug(tmpDir)
    defer f.Close()
    defer func() {
        err = os.RemoveAll("plugin/template/upload")
        if err != nil {
            beego.Error(err)
        }
    }()
 
    //上传目标文件
    destFile := filepath.Join(tmpDir, fh.Filename)
    err = this.SaveToFile(fileKey, destFile)
    if err != nil {
        result.GenerateErrorApiResult(fmt.Sprintf("上传目标文件错误,错误原因为:[ %s ]", err.Error()))
        beego.Error(result.Error.Msg)
        this.ServeJSON()
        return
    }
 
    count, err := cpt.Import(destFile)
    if err != nil {
        result.GenerateErrorApiResult(fmt.Sprintf("导入文件失败,错误原因为:[ %s ]", err.Error()))
        beego.Error(result.Error.Msg)
        this.ServeJSON()
        return
    }
    data := make(map[string]interface{})
    data["items"] = count
    result.GenerateSuccessApiResult(data)
    beego.Debug("上传文件参数:", destFile)
    this.ServeJSON()
}

猜你喜欢

转载自www.cnblogs.com/craneboos/p/8985086.html