/** * 上传话题图片 */ func actionUpimg(ctx *goku.HttpContext) goku.ActionResulter { var ok = false var errs string topicId, err := strconv.ParseInt(ctx.RouteData.Params["id"], 10, 64) if err == nil && topicId > 0 { imgFile, header, err2 := ctx.Request.FormFile("topic-image") err = err2 defer func() { if imgFile != nil { imgFile.Close() } }() if err == nil { ext := path.Ext(header.Filename) if acceptFileTypes.MatchString(ext[1:]) == false { errs = "错误的文件类型" } else { sid := strconv.FormatInt(topicId, 10) saveDir := path.Join(ctx.RootDir(), golink.PATH_IMAGE_AVATAR, "topic", sid[len(sid)-2:]) err = os.MkdirAll(saveDir, 0755) if err == nil { saveName := fmt.Sprintf("%v_%v%v", strconv.FormatInt(topicId, 36), strconv.FormatInt(time.Now().UnixNano(), 36), ext) savePath := path.Join(saveDir, saveName) var f *os.File f, err = os.Create(savePath) defer f.Close() if err == nil { _, err = io.Copy(f, imgFile) if err == nil { // update to db _, err2 := models.Topic_UpdatePic(topicId, path.Join(sid[len(sid)-2:], saveName)) err = err2 if err == nil { ok = true } } } } } } } else if topicId < 1 { errs = "参数错误" } if err != nil { errs = err.Error() } r := map[string]interface{}{ "success": ok, "errors": errs, } return ctx.Json(r) }