您好,登錄后才能下訂單哦!
使用golang怎么實(shí)現(xiàn)一個(gè)文件上傳服務(wù),很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
package main import ( "encoding/json" "io" "math/rand" "net/http" "os" "strconv" "strings" "time" ) const POS = "." const DIR = "/" const PATH = "image" const HTTP = "https://www.image.com" func getFileName(ext string) string { random := rand.New(rand.NewSource(time.Now().UnixNano())) datetime := time.Now().Format("200612") dstPath := PATH + DIR + datetime dstFile := dstPath + DIR + datetime + strconv.Itoa(random.Int()) + POS + strings.Replace(ext, DIR, POS, 1) _, err := os.Stat(dstPath) res := os.IsNotExist(err) if res == true { os.MkdirAll(dstPath, os.ModePerm) } return dstFile } func uploadFile(w http.ResponseWriter, r *http.Request) { r.ParseMultipartForm(10 << 20) file, handler, err := r.FormFile("myFile") if err != nil { w.WriteHeader(500) return } defer file.Close() fileName := getFileName(handler.Header.Get("Content-Type")) fp, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { w.WriteHeader(500) return } defer fp.Close() size, err := io.Copy(fp, file) if err != nil { w.WriteHeader(500) return } go callUploadResult(w, fileName, size) } func callUploadResult(w http.ResponseWriter, fileName string, size int64) { var list = make(map[string]string) list["image"] = HTTP + DIR + fileName list["size"] = strconv.FormatInt(size/1024, 10) + "KB" list["action"] = "call-upload-result" jsonStr, _ := json.Marshal(list) w.Header().Set("Content-Type", "application/json") w.Write([]byte(jsonStr)) } func main() { http.HandleFunc("/upload", uploadFile) http.ListenAndServe("127.0.0.1:8090", nil) }
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。