Esempio n. 1
0
func (m *Attach) GetByIds(ids []bson.ObjectId) []models.AttachModel {
	// TODO cache data.

	attaches := []models.AttachModel{}
	models.NewAttach().FindAll(models.M{"_id": models.M{"$in": ids}}, "", 0, 0, false, &attaches)

	return attaches
}
Esempio n. 2
0
func Upload(r *http.Request) (*models.AttachModel, error) {
	uploadRoot, err := getUploadRoot()
	if err != nil {
		return nil, err
	}

	// 获取上传文件数据
	file, handler, err := r.FormFile("file")
	if err != nil {
		file, handler, err = r.FormFile("Filedata")
	}
	if err != nil {
		return nil, nil
	}

	extension := strings.TrimLeft(strings.ToLower(filepath.Ext(handler.Filename)), ".")
	switch extension {
	case "gif", "jpg", "jpeg", "png":
	default:
		return nil, errors.New("20106")
	}

	// 获取文件存储路径
	saveHost := ""
	savePath, saveName := HelperForFilePathCreator(uploadRoot, handler.Filename, true)

	data, err := ioutil.ReadAll(file)
	if err != nil {
		return nil, err
	}

	size := len(data)
	if size > 5242880 { // 文件容量大小不能超过 5M
		return nil, errors.New("20107")
	}

	// get file hash
	h := md5.New()
	h.Write(data)
	hash := fmt.Sprintf("%s", hex.EncodeToString(h.Sum(nil)))

	// to check is whether same file. 如果存在相同的,就直接返回.
	model := models.NewAttach()
	//old                 := &models.AttachModel{}
	//model.Find(models.M{"hash":hash}, old)
	//if old.Id.Valid() { return old, nil }

	// 不存在相同的文件,就创建.
	err = ioutil.WriteFile(uploadRoot+"/"+savePath+"/"+saveName+"."+extension, data, 0644)
	if err != nil {
		return nil, errors.New("20110")
	}

	// 存储图片数据到库中
	attach := &models.AttachModel{
		Id:       model.GetID(),
		Name:     handler.Filename,
		Size:     size,
		Ext:      extension,
		Hash:     hash,
		SaveHost: saveHost,
		SavePath: savePath,
		SaveName: saveName + "." + extension,
	}

	// 当有图片集群存在时,需要自动异步同步当前上传图片到所有其他服务器上。
	if len(StaticHosts) > 0 {
		WaitSyncFiles = append(WaitSyncFiles, uploadRoot+"/"+savePath+"/"+saveName+"."+extension)
	}
	// attach.Self = attach
	// err     = attach.Save(true)
	// if err != nil { return nil, err }

	return attach, nil
}