增加下载上传功能

This commit is contained in:
lupeng 2025-08-01 16:42:58 +08:00
parent 8aca18c54d
commit ba787bd601
4 changed files with 390 additions and 18 deletions

Binary file not shown.

363
main.go
View File

@ -2,6 +2,7 @@ package main
import (
"fmt"
"io"
"math"
"net/http"
"sort"
@ -1199,11 +1200,18 @@ func initwellParaUnitMap() {
}
func fileServerG() {
// http.Handle("/file", http.FileServer(http.Dir("E:/Code/old/deesCloud/deescloud/authfile")))
http.Handle("/file/", http.StripPrefix("/file/", http.FileServer(http.Dir(modelePath+"/authfile"))))
err := http.ListenAndServe("0.0.0.0:8881", nil)
if err != nil {
fmt.Println("服务器错误8884")
fmt.Println("服务器错误8881")
}
}
func uploadFile() {
http.Handle("/upload/", http.StripPrefix("/upload/", http.FileServer(http.Dir(modelePath+"/upload"))))
err := http.ListenAndServe("0.0.0.0:8882", nil)
if err != nil {
fmt.Print(err)
}
}
@ -1316,6 +1324,7 @@ func main() {
//fileserver
go fileServerG()
go uploadFile()
http.HandleFunc("/test", test)
@ -1535,6 +1544,10 @@ func main() {
http.HandleFunc("/deescloud/get_tool_WarningCsv", get_tool_WarningCsv)
http.HandleFunc("/deescloud/getInstrumentMess", getInstrumentMess)
http.HandleFunc("/deescloud/addQualityData", addQualityData)
http.HandleFunc("/deescloud/getQualityData", getQualityData)
http.HandleFunc("/deescloud/upload", upload)
http.HandleFunc("/deescloud/download_ds_file", download_ds_file)
//监听服务
fmt.Println("listen server ...")
@ -3599,7 +3612,7 @@ func GenerateInstrumentPDF(fullData []byte, resp []Tool_warning) (filename strin
pdf.SetX(margin)
pdf.SetY(y)
reportTime := time.Now().Format("2006-01-02 15:04:05")
pdf.Cell(nil, fmt.Sprintf("井号:%s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t报告时间:%s", wellName, reportTime))
pdf.Cell(nil, fmt.Sprintf("井号:%s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t报告时间:%s", wellName, reportTime))
y += lineHeight * 1.2
pdf.Line(margin, y, pageWidth-margin, y)
y += 10
@ -30072,7 +30085,7 @@ func getInstrumentMessUtil(req InstrumentMess) (*InstrumentMessRespdata, error)
}
fmt.Println("")
//上井情况汇总
resp.WorkMessList = workMess(wellInfos, req.Flag, req.Content, req.WellName)
resp.WorkMessList = workMess(wellInfos, req.Flag, req.Content)
//维保情况
resp.GetLcmRespData = getMaintenanceMess(req.Series, req.Instrument, req.Opuser)
//仪器所在部门
@ -30082,7 +30095,7 @@ func getInstrumentMessUtil(req InstrumentMess) (*InstrumentMessRespdata, error)
return resp, nil
}
func workMess(wellInfos []get_vibration_resp, flag string, content string, WellName string) []WellMessRespdata {
func workMess(wellInfos []get_vibration_resp, flag string, content string) []WellMessRespdata {
var results []WellMessRespdata
if len(wellInfos) == 0 {
@ -30095,6 +30108,7 @@ func workMess(wellInfos []get_vibration_resp, flag string, content string, WellN
// 循环打印每个 WellNameSource
fmt.Println("开始打印 WellNameSource 列表:")
workMessSql := `SELECT
MAX(id) AS id,
[5200] AS WellName,
(SELECT TOP 1 [5203]
FROM [dbo].[EQUIPMENTRECORDS] t2
@ -30135,6 +30149,7 @@ func workMess(wellInfos []get_vibration_resp, flag string, content string, WellN
continue
}
defer conn.Close()
rows, err := conn.Query(qsql)
if err != nil {
fmt.Println("查询工作状态出错", err.Error())
@ -30142,28 +30157,66 @@ func workMess(wellInfos []get_vibration_resp, flag string, content string, WellN
}
defer rows.Close()
fmt.Println("查询数据库------------------", qsql)
for rows.Next() {
var item WellMessRespdata
var wellName, sampleField, valueInterval, personnelList, globalMax1, globalMax2 string
err := rows.Scan(&wellName, &sampleField, &valueInterval, &globalMax1, &globalMax2, &personnelList)
if err != nil {
var id, wellName, sampleField, valueInterval, personnelList, globalMax1, globalMax2 string
//先扫描工作数据
if err := rows.Scan(&id, &wellName, &sampleField, &valueInterval, &globalMax1, &globalMax2, &personnelList); err != nil {
fmt.Println("扫描数据失败", db, err.Error())
continue
}
// 映射到结构体
//查询上传文件数据
queryUploadSql := `SELECT id, file_name, create_user, create_time, well_file_id, type
FROM t_file
WHERE type='tool_detail' AND well_file_id=@wellFileId`
uploadRows, err := sqlConn.Query(queryUploadSql, sql.Named("wellFileId", id))
if err != nil {
fmt.Printf("查询上传数据失败: %v\n", err)
continue
}
var uploadData []uploadRes
for uploadRows.Next() {
var res uploadRes
if err := uploadRows.Scan(
&res.ID,
&res.FileName,
&res.CreateUser,
&res.CreateTime,
&res.WellFileId,
&res.Types,
); err != nil {
fmt.Printf("扫描上传数据行失败: %v\n", err)
continue
}
uploadData = append(uploadData, res)
}
uploadRows.Close()
// 3. 填充数据
fmt.Printf("扫描到的值 - ID: %s, WellName: %s, SampleField: %s, ValueInterval: %s, GlobalMax1: %s, GlobalMax2: %s, PersonnelList: %s\n",
id, wellName, sampleField, valueInterval, globalMax1, globalMax2, personnelList)
item.ID = id
item.WellName = wellName
item.SampleField = sampleField
item.ValueInterval = valueInterval
item.GlobalMax1 = globalMax1
item.GlobalMax2 = globalMax2
item.PersonnelList = personnelList
item.Data = uploadData // 添加上传数据
if flag == "0" {
item.Content = "正常"
} else {
item.Content = content
}
item.Flag = flag
results = append(results, item)
}
}
@ -30295,6 +30348,296 @@ func get_DeptMess(series string, instrument string) string {
}
}
func addQualityData(response http.ResponseWriter, request *http.Request) {
beginTime := time.Now().UnixNano()
fmt.Println("addQualityData recv req begin", time.Now().Format("2006-01-02 15:04:05"))
reqdata, _ := ioutil.ReadAll(request.Body)
var req QualityData
json.Unmarshal(reqdata, &req)
// 确定要更新的字段名
var fieldName string
switch req.Field {
case "process_record":
fieldName = "process_record"
case "process_inspection":
fieldName = "process_inspection"
case "final_inspection":
fieldName = "final_inspection"
default:
// 如果字段不匹配,返回错误
response.WriteHeader(http.StatusBadRequest)
response.Write([]byte(`{"code": 1, "msg": "无效的字段类型"}`))
return
}
// 构建查询语句,检查记录是否存在
// 安全警告当前代码存在SQL注入风险建议使用参数化查询
querySQL := fmt.Sprintf(`SELECT id
FROM t_quality_inspection
WHERE well_name = '%s' AND series = '%s' AND instrument = '%s'`,
req.WellName, req.Series, req.Instrument)
fmt.Println("querySQL----", querySQL)
row := sqlConn.QueryRow(querySQL) // 使用QueryRow获取单行结果
var fieldValue sql.NullString // 使用NullString处理可能为NULL的情况
err := row.Scan(&fieldValue)
var exists bool
if err != nil {
if err == sql.ErrNoRows {
exists = false // 没有找到记录
} else {
fmt.Println("查询质量检验数据失败:", err)
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"code": 1, "msg": "数据库查询失败"}`))
return
}
} else {
// 检查字段是否有值非NULL且非空字符串
exists = fieldValue.Valid && fieldValue.String != ""
}
// 现在可以使用exists变量
fmt.Printf("字段 '%s' 是否有值: %t\n", req.Field, exists)
// 获取当前时间
currentTime := time.Now().Format("2006-01-02 15:04:05")
if exists {
// 记录存在,执行更新操作
updateSQL := fmt.Sprintf(`UPDATE t_quality_inspection
SET %s = '%s', update_time = '%s', update_user = '%s'
WHERE well_name = '%s' AND series = '%s' AND instrument = '%s'`,
fieldName, req.Value, currentTime, req.OpUser, req.WellName, req.Series, req.Instrument)
fmt.Println("updateSQL----", updateSQL)
_, err := sqlConn.Exec(updateSQL)
if err != nil {
fmt.Println("更新质量检验数据失败:", err)
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"code": 1, "msg": "数据更新失败"}`))
return
}
} else {
// 记录不存在,执行插入操作
insertSQL := fmt.Sprintf(`INSERT INTO t_quality_inspection
(create_time, update_time, create_user, update_user, %s, well_name, series, instrument)
VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')`,
fieldName, currentTime, currentTime, req.OpUser, req.OpUser, req.Value, req.WellName, req.Series, req.Instrument)
fmt.Println("insertSQL----", insertSQL)
_, err := sqlConn.Exec(insertSQL)
if err != nil {
fmt.Println("插入质量检验数据失败:", err)
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"code": 1, "msg": "数据插入失败"}`))
return
}
}
// 返回成功响应
responseData := map[string]interface{}{
"code": 0,
"msg": "操作成功",
"data": nil,
}
jsonResponse, _ := json.Marshal(responseData)
response.Write(jsonResponse)
fmt.Println("addQualityData recv req end", time.Now().Format("2006-01-02 15:04:05"), "cost:", (time.Now().UnixNano()-beginTime)/1e6, "ms")
}
func getQualityData(response http.ResponseWriter, request *http.Request) {
beginTime := time.Now().UnixNano()
fmt.Println("getQualityData recv req begin", time.Now().Format("2006-01-02 15:04:05"))
// 读取并解析请求体
reqdata, err := ioutil.ReadAll(request.Body)
if err != nil {
response.WriteHeader(http.StatusBadRequest)
response.Write([]byte(`{"code": 1, "msg": "读取请求体失败"}`))
return
}
var req QualityData
if err := json.Unmarshal(reqdata, &req); err != nil {
response.WriteHeader(http.StatusBadRequest)
response.Write([]byte(`{"code": 1, "msg": "解析请求体失败"}`))
return
}
// 验证必填字段
if req.Series == "" || req.Instrument == "" || req.Field == "" {
response.WriteHeader(http.StatusBadRequest)
response.Write([]byte(`{"code": 1, "msg": "缺少必要参数"}`))
return
}
// 查询数据库
querySQL := fmt.Sprintf(`SELECT COALESCE(process_record, '') as process_record ,COALESCE(process_inspection, '') as process_inspection ,COALESCE(final_inspection, '') as final_inspection
FROM t_quality_inspection
WHERE well_name = '%s' AND series = '%s' AND instrument = '%s'`,
req.WellName, req.Series, req.Instrument)
fmt.Println("querySQL----", querySQL)
var resp QualityDataResp
err = sqlConn.QueryRow(querySQL).Scan(
&resp.ProcessRecord,
&resp.ProcessInspection,
&resp.FinalInspection,
)
if err != nil {
if err == sql.ErrNoRows {
fmt.Println("未查询到数据:", err)
// 没有找到记录,返回空值
resp = QualityDataResp{}
} else {
// 数据库查询出错
fmt.Println("查询质量检验数据失败:", err)
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"code": 1, "msg": "数据库查询失败"}`))
return
}
}
fmt.Println("查询质量检验数据成功:", resp)
// 构造响应
responseData := map[string]interface{}{
"code": 0,
"msg": "操作成功",
"data": resp,
}
jsonResponse, err := json.Marshal(responseData)
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"code": 1, "msg": "生成响应失败"}`))
return
}
response.Header().Set("Content-Type", "application/json")
response.Write(jsonResponse)
fmt.Println("getQualityData recv req end", time.Now().Format("2006-01-02 15:04:05"), "cost:", (time.Now().UnixNano()-beginTime)/1e6, "ms")
}
func upload(response http.ResponseWriter, request *http.Request) {
beginTime := time.Now().UnixNano()
fmt.Println("upload recv req begin", time.Now().Format("2006-01-02 15:04:05"))
// 解析 multipart 表单,最大内存为 32MB
err := request.ParseMultipartForm(32 << 20)
if err != nil {
logs.Error("解析表单失败:", err)
response.WriteHeader(http.StatusBadRequest)
response.Write([]byte(`{"code": 1, "msg": "解析表单失败"}`))
return
}
// 获取文件句柄和文件头
file, handler, err := request.FormFile("file")
if err != nil {
logs.Error("获取上传文件失败:", err)
response.WriteHeader(http.StatusBadRequest)
response.Write([]byte(`{"code": 1, "msg": "获取上传文件失败"}`))
return
}
defer file.Close()
// 获取其他表单字段
id := request.FormValue("id")
wellName := request.FormValue("wellName")
opuser := request.FormValue("opuser")
types := request.FormValue("type")
// 创建保存文件的目录(如果不存在)
saveDir := "./upload"
if _, err := os.Stat(saveDir); os.IsNotExist(err) {
os.MkdirAll(saveDir, 0755)
}
// 构造文件保存路径
filename := fmt.Sprintf("%s/%s", saveDir, handler.Filename)
// 创建文件
f, err := os.Create(filename)
if err != nil {
logs.Error("创建文件失败:", err)
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"code": 1, "msg": "创建文件失败"}`))
return
}
defer f.Close()
// 将上传的文件内容复制到新创建的文件中
_, err = io.Copy(f, file)
if err != nil {
logs.Error("保存文件失败:", err)
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"code": 1, "msg": "保存文件失败"}`))
return
}
// 返回成功响应
responseData := map[string]interface{}{
"code": 0,
"msg": "文件上传成功",
"data": map[string]string{
"id": id,
"wellName": wellName,
"opuser": opuser,
"type": types,
"filename": filename,
"fileSize": fmt.Sprintf("%d", handler.Size),
},
}
insert_sql := fmt.Sprintf(`INSERT INTO [t_file]
([well_file_id]
,[file_name]
,[create_user]
,[type]
,[create_time])
VALUES
('%s'
,'%s'
,'%s','%s','%s')`, id, filename, opuser, types, time.Now().Format("2006-01-02 15:04:05"))
_, err = sqlConn.Exec(insert_sql)
if err != nil {
fmt.Println(fmt.Sprintf(`%s err:%s`, insert_sql, err.Error()))
}
jsonResponse, _ := json.Marshal(responseData)
response.Write(jsonResponse)
fmt.Println("upload recv req end", time.Now().Format("2006-01-02 15:04:05"), "cost:", (time.Now().UnixNano()-beginTime)/1e6, "ms")
}
func download_ds_file(rw http.ResponseWriter, r *http.Request) {
//获取请求参数
filename := r.FormValue("id")
fmt.Println("filename------", filename)
base_file_path := modelePath + "/upload/"
if filename != "" {
//设置响应头
header := rw.Header()
header.Add("Content-Type", "application/octet-stream")
//使用ioutil包读取文件
filepath := base_file_path + filename
fmt.Println(filepath)
b, _ := ioutil.ReadFile(filepath)
//写入到响应流中
rw.Write(b)
}
}
// 跨域测试
func test(response http.ResponseWriter, request *http.Request) {
fmt.Println("recv test req")

10
req.go
View File

@ -666,3 +666,13 @@ type InstrumentMess struct {
Flag string `json:"flag"`
Content string `json:"content"`
}
type QualityData struct {
Field string `json:"field"` //类型
Series string `json:"series"`
Instrument string `json:"instrument"`
OpUser string `json:"opuser"`
Opuser_uuid string `json:"opuser_uuid"`
WellName string `json:"wellName"`
Value string `json:"value"`
}

35
res.go
View File

@ -745,6 +745,7 @@ type InstrumentMessRespdata struct {
ID string `json:"id"`
WellName string `json:"wellName"` //井名称
Time string `json:"time"` //出厂日期
HouseDate string `json:"houseDate"` //入库日期
Series string `json:"series"` //系列号
Instrument string `json:"instrument"` //仪器号
Version string `json:"version"` //版本号
@ -759,12 +760,30 @@ type InstrumentMessRespdata struct {
// 上井情况汇总
type WellMessRespdata struct {
WellName string `json:"wellName"` //井名称
SampleField string `json:"sampleField"` //入井状态
ValueInterval string `json:"valueInterval"` //入井井深
GlobalMax1 string `json:"globalMax1"` //最高工作温度
GlobalMax2 string `json:"globalMax2"` //最高承压
PersonnelList string `json:"personnelList"` //累计工作时间
Content string `json:"content"` //仪器工作情况
Flag string `json:"flag"` //仪器工作情况标识
ID string `json:"id"` //唯一标识
WellName string `json:"wellName"` //井名称
SampleField string `json:"sampleField"` //入井状态
ValueInterval string `json:"valueInterval"` //入井井深
GlobalMax1 string `json:"globalMax1"` //最高工作温度
GlobalMax2 string `json:"globalMax2"` //最高承压
PersonnelList string `json:"personnelList"` //累计工作时间
Content string `json:"content"` //仪器工作情况
Flag string `json:"flag"` //仪器工作情况标识
Data []uploadRes `json:"data"`
}
type QualityDataResp struct {
ProcessRecord string `json:"process_record"`
ProcessInspection string `json:"process_inspection"`
FinalInspection string `json:"final_inspection"`
}
type uploadRes struct {
ID string `json:"id"`
FileName string `json:"fileName"`
RealFileName string `json:"realFileName"`
CreateUser string `json:"createUser"`
CreateTime string `json:"createTime"`
WellFileId string `json:"wellFileId"`
Types string `json:"type"`
}