예제 #1
0
파일: view.go 프로젝트: tjz101/caffbox
func thumbnail(filePath string, resize string) (string, error) {
	preFilePath := filePath
	filePath = filepath.Join(filepath.Dir(preFilePath), resize, filepath.Base(preFilePath))
	if preFilePath != filePath {
		m := &sync.Mutex{}
		m.Lock()
		defer m.Unlock()
		fla, _ := util.FileExists(filePath)
		if !fla {
			newFilePath := filepath.Dir(filePath)
			fla, _ := util.DirExists(newFilePath)
			if !fla {
				err := util.Mkdir(newFilePath)
				if err != nil {
					return preFilePath, err
				}
			}
			cmdFormat := "convert %s -resize %s %s"
			cmd := fmt.Sprintf(cmdFormat, preFilePath, resize, filePath)
			list := strings.Split(cmd, " ")
			c := exec.Command(list[0], list[1:]...)
			err := c.Run()
			if err != nil {
				return preFilePath, err
			}
			return filePath, nil
		} else {
			return filePath, nil
		}
	}
	return preFilePath, nil
}
예제 #2
0
func writeFileToPath(path string, file multipart.File, watermark string, header *multipart.FileHeader) (caffbox.Response, error) {
	if path == "" {
		path = util.PathFromTime()
	}
	physicalPath := util.GetPhysicalPath(path)

	err := util.Mkdir(physicalPath)
	if err != nil {
		return caffbox.Response{ErrCode: caffbox.CODE_DIR_CREATE_FAILED, ErrMsg: caffbox.MSG_DIR_CREATE_FAILED}, err
	}

	destFilename := header.Filename
	if caffbox.Sett.Rename {
		destFilename = util.RandomString()
		destFilename = destFilename + util.GetFileSuffix(header.Filename)
	}
	filePhysicalPath := filepath.Join(physicalPath, destFilename)
	fla, err := util.FileExists(filePhysicalPath)
	if fla && err == nil {
		newFilename, err := util.IncreaseFilename(physicalPath, destFilename)
		if newFilename == destFilename || err != nil {
			return caffbox.Response{ErrCode: caffbox.CODE_FILE_ALREADY_EXISTS, ErrMsg: caffbox.MSG_FILE_ALREADY_EXISTS}, err
		} else {
			destFilename = newFilename
		}
		filePhysicalPath = filepath.Join(physicalPath, newFilename)
	}
	destFile, err := os.OpenFile(filePhysicalPath, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		return caffbox.Response{ErrCode: caffbox.CODE_FILE_OPEN_FAILED, ErrMsg: caffbox.MSG_FILE_OPEN_FAILED}, err
	}
	defer destFile.Close()
	_, err = io.Copy(destFile, file)
	if err != nil {
		return caffbox.Response{ErrCode: caffbox.CODE_FILE_SAVE_FAILED, ErrMsg: caffbox.MSG_FILE_SAVE_FAILED}, err
	}
	if watermark == "y" && caffbox.Sett.Watermark != "" {
		cmdFormat := "composite -gravity center %s %s %s"
		cmd := fmt.Sprintf(cmdFormat, caffbox.Sett.Watermark, filePhysicalPath, filePhysicalPath)
		list := strings.Split(cmd, " ")
		c := exec.Command(list[0], list[1:]...)
		err := c.Run()
		if err != nil {
			return caffbox.Response{ErrCode: caffbox.CODE_FILE_SAVE_FAILED, ErrMsg: caffbox.MSG_FILE_SAVE_FAILED}, err
		}
	}
	absPath, _ := util.GetAbsPath(physicalPath)
	return caffbox.Response{ErrCode: caffbox.CODE_SUCCESS, ErrMsg: caffbox.MSG_SUCCESS, Data: caffbox.CaffFile{Name: destFilename, Path: absPath, OriginalName: header.Filename}}, nil
}