예제 #1
0
func (pc *PicCloud) Sign(userid string, expire uint) (string, error) {
	return sign.AppSignV2(pc.Appid, pc.SecretId, pc.SecretKey, pc.Bucket, expire, userid)
}
예제 #2
0
func (pc *PicCloud) UploadBase(userid string, filename string, fileid string, analyze PicAnalyze) (info UrlInfo, err error) {
	if "" == filename {
		err = errors.New("invliad filename")
		return
	}

	reqUrl := pc.getUrl(userid, fileid)
	boundary := "-------------------------abcdefg1234567"
	expire := uint(3600)

	var queryString string
	if analyze.Fuzzy != 0 {
		queryString += "fuzzy."
	}
	if analyze.Food != 0 {
		queryString += "food."
	}
	if queryString != "" {
		reqUrl += "?analyze=" + strings.TrimRight(queryString, ".")
	}

	sign, err := sign.AppSignV2(pc.Appid, pc.SecretId, pc.SecretKey, pc.Bucket, expire, userid)
	if nil != err {
		return
	}

	bodyBuf := &bytes.Buffer{}
	bodyWriter := multipart.NewWriter(bodyBuf)
	bodyWriter.SetBoundary(boundary)
	fileWriter, err := bodyWriter.CreateFormFile("FileContent", filename)
	if nil != err {
		return
	}
	fh, err := os.Open(filename)
	if nil != err {
		return
	}
	_, err = io.Copy(fileWriter, fh)
	if nil != err {
		return
	}
	bodyWriter.Close()

	req, err := http.NewRequest("POST", reqUrl, bodyBuf)
	if nil != err {
		return
	}
	req.Header.Set("HOST", "web.image.myqcloud.com")
	req.Header.Set("user-agent", "qcloud-go-sdk")
	req.Header.Set("Authorization", "QCloud "+sign)
	req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)

	var client http.Client
	resp, err := client.Do(req)
	if nil != err {
		fmt.Printf("http error, err=%s", err.Error())
		return
	}
	defer resp.Body.Close()

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

	code, message, js, err := pc.parseRsp(data)
	if nil != err {
		return
	}
	if code != 0 {
		desc := fmt.Sprintf("rsp error, code=%d, message=%s", code, message)
		err = errors.New(desc)
		return
	}

	info.Url, _ = js.Get("data").Get("url").String()
	info.DownloadUrl, _ = js.Get("data").Get("download_url").String()
	info.Fileid, _ = js.Get("data").Get("fileid").String()
	if nil != js.Get("data").Get("is_fuzzy") {
		info.Analyze.Fuzzy, _ = js.Get("data").Get("is_fuzzy").Int()
	}
	if nil != js.Get("data").Get("is_food") {
		info.Analyze.Food, _ = js.Get("data").Get("is_food").Int()
	}
	return
}