78.上傳文件及在服務(wù)器保存文件到任意路徑

上傳文件到服務(wù)器是一個常用的操作,而在服務(wù)器上保存文件就需要多多用心了。因為你不可能只在一個路徑里保存文件她倘,所以需要實踐一下保存文件到任意位置。當然作箍,前提是你的應(yīng)用程序有這樣的操作權(quán)限硬梁。
首先建立一個main.go文件,作為項目的起點胞得。并使用一個網(wǎng)頁模板JoelUploadFile.html荧止,作為操作界面。


代碼目錄結(jié)構(gòu)

在main文件中阶剑,準備好頁面路徑跃巡、上傳路徑、文件訪問路徑等个扰,及相對應(yīng)函數(shù)

/**
* CofoxS
* @Author:  Jian Junbo
* @Email:   junbojian@qq.com
* @Create:  2019/3/30 22:25
* Copyright (c) 2019 Jian Junbo All rights reserved.
*
* Description:  
*/
package main

import (
    "fmt"
    "goHttps/uilFileSys"
    "html/template"
    "log"
    "net/http"
)

func main() {
    fmt.Println("Hello Moon!")
    log.Println("隨意指定文件保存路徑!")

    //--頁面路徑
    http.HandleFunc("/", IndexHandler)

    //--上傳文件
    http.HandleFunc("/fileSys/tmpUpload/", uilFileSys.FileTmpUpload)

    //----上傳文件
    http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("tmp"))))

    websitename := ":90"
    http.ListenAndServe(websitename, nil)
}

func IndexHandler(writer http.ResponseWriter, request *http.Request) {
    //取消獲取facicon.ico的訪問
    if request.RequestURI == "/facicon.ico" {
        return
    }

    //---------綁定模板頁 begin-------------
    t, err := template.ParseFiles("./templatefile/JoelUploadFile.html")
    if err != nil {
        fmt.Println("發(fā)生了錯誤瓷炮!")
        fmt.Fprintln(writer, err)
    }

    t.ExecuteTemplate(writer, "JoelUploadFile.html", "")
    //---------綁定模板頁 end---------------
}

需要綁定的模板文件 JoelUploadFile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>企業(yè)上傳文件</title>
    <style type="text/css">

        input{
            line-height: 20px;
            padding-left: 2px;
            padding-right: 2px;
            margin-left: 2px;
            margin-right: 2px;
            background-color: #eaf4fc;
            border-color: #b5c1e4;
            border-width: 1px;
            border-style: solid;
            border-radius: 3px;
        }

        /*上傳文件*/
        .file {
            position: relative;
            display: inline-block;
            background: #D0EEFF;
            border: 1px solid #99D3F5;
            border-radius: 4px;
            padding: 4px 12px;
            overflow: hidden;
            color: #1E88C7;
            text-decoration: none;
            text-indent: 0;
            line-height: 20px;
        }

        .file input {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
        }

        .file:hover {
            background: #AADFFD;
            border-color: #78C3F3;
            color: #004974;
            text-decoration: none;
        }


    </style>
    <script type="text/javascript">
        /*同步數(shù)據(jù)*/
        function synkFile(srcObj, showObj, newObj) {
            var srcO = document.getElementById(srcObj);
            var showO = document.getElementById(showObj);
            var new0 = document.getElementById(newObj);
            /*if (srcO.value.length > 0) {
                showO.value = srcO.value;
            }
            */

            // showO.value = "";
            new0.innerText = "";
            for (var i = 0; i < srcO.files.length; i++) {
                // showO.value += srcO.files[i].name + "|";
                new0.innerText += srcO.files[i].name + "|\r\n";
            }
        }
        /*保存修改數(shù)據(jù)*/
        function saveF() {
            var frm = document.getElementById("formSave");
            var u_id = document.getElementById("u_Id");
            if (u_id.value.length <= 0) {
                alert('\'流水號\'丟失!');
                return;
            }
            frm.submit();
        }
    </script>
</head>
<body>
<div>企業(yè)上傳文件递宅,按照“平臺》企業(yè)編號》系統(tǒng)》年月日”來儲存文件娘香,文件名使用生成時間</div>
<div>
    <form id="formSave"  enctype="multipart/form-data" action="/fileSys/tmpUpload/" method="post">
        <input id="u_Id" name="u_Id" type="text" value="joel"
               style="width: 500px; display: none;" readonly>
        <a href="javascript:;" class="file">上傳附件<input type="file" id="uploadfile" name="uploadfile" multiple
                                                       style="cursor: pointer"
                                                       onchange="synkFile('uploadfile','u_ElectranicAttachment','new_ElectranicAttachment')"></a>
        <label id="show_ElectranicAttachment"></label>
        <label id="new_ElectranicAttachment"></label>
        <input id="u_ElectranicAttachment" name="u_ElectranicAttachment" type="text" value=""
               style="display: none">

        <div><input type="button" value="保存"  onclick="saveF()"></div>
    </form>
</div>
</body>
</html>

實現(xiàn)上傳功能的函數(shù)

/**
* CofoxS
* @Author:  Jian Junbo
* @Email:   junbojian@qq.com
* @Create:  2019/3/31 23:27
* Copyright (c) 2019 Jian Junbo All rights reserved.
*
* Description:  企業(yè)文件管理
*/
package uilFileSys

import (
    "cofoxWebPlatform/platform/lib"
    "cofoxWebPlatform/platform/model"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "path"
)

//上傳文件到臨時文件路徑,前提條件是當前用戶是在線用戶
func FileTmpUpload(writer http.ResponseWriter, request *http.Request)  {
    //接收數(shù)據(jù)
    keyId := request.FormValue("keyId")     //key身份Id

    //get a ref to the parsed  multipart form
    m := request.MultipartForm
    //get the *fileheaders
    files := m.File["uploadfile"]
    for i,_ := range files  {
        //save the file as filename
        filename := lib.JoelGetNowFullTimeNumber() +  path.Ext(files[i].Filename)

        //for each fileheader, get a handle to the actual file
        file, err := files[i].Open()
        defer file.Close()
        if err != nil {
            http.Error(writer, err.Error(), http.StatusInternalServerError)
            return
        }
        //create destination file making sure the path is writeable.
        dst, err := os.Create("./tmp/" + filename)
        defer dst.Close()
        if err != nil {
            http.Error(writer, err.Error(), http.StatusInternalServerError)
            return
        }
        //copy the uploaded file to the destination file
        if _, err := io.Copy(dst, file); err != nil {
            http.Error(writer, err.Error(), http.StatusInternalServerError)
            return
        }

        tmpfile := dst.Name()    // 寫入保存文件的位置和文件名

        lib.JoelLog(keyId,tmpfile)  //服務(wù)端輸出
        resultValue := model.JoelBaseAskResultNormal{}
        resultValue.AskResult = tmpfile
        back,_ := json.Marshal(resultValue)
        fmt.Fprint(writer,string(back)) //返回客端數(shù)據(jù)
    }
}

運行此程序


服務(wù)器顯示

瀏覽器顯示

點擊“上傳附件”办龄,選擇要上傳的文件烘绽。


選擇一個圖片文件

點擊“保存”按鈕,激發(fā)js的saveF()函數(shù)俐填,提交form到服務(wù)器
一般都會順帶提交一些其他數(shù)據(jù)安接,例如:u_Id

提交后,文件保存到 "/tmp/" 路徑英融,這個路徑在當前程序的根上盏檐。
已上傳到服務(wù)器的文件

服務(wù)器返回的json串
下面可以指定保存的其他路徑

當前文件保存的位置是 tmp 路徑歇式,是在 \uilFileSys\EntFileMS.go 中定義的

        //create destination file making sure the path is writeable.
        dst, err := os.Create("./tmp/" + filename)

用windows系統(tǒng)來舉例,如果我希望文件保存在另一個位置胡野,比如:e盤材失,這行代碼只需要修改為

        //create destination file making sure the path is writeable.
        dst, err := os.Create("e://" + filename)

如果,你上傳之后硫豆,還想能夠通過瀏覽器訪問到這個文件龙巨,那么在 main.go 中,有這樣的一行代碼

    //----上傳文件
    http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("tmp"))))

你需要把它改成

    //----上傳文件
    http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("e:\\"))))

至此熊响,大功告成旨别!你已經(jīng)可以把文件上傳到 e 盤了。
在此基礎(chǔ)上汗茄,你應(yīng)該可以動態(tài)的指定每次上傳文件的物理路徑了秸弛。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市洪碳,隨后出現(xiàn)的幾起案子胆屿,更是在濱河造成了極大的恐慌,老刑警劉巖偶宫,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件非迹,死亡現(xiàn)場離奇詭異,居然都是意外死亡纯趋,警方通過查閱死者的電腦和手機憎兽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來吵冒,“玉大人纯命,你說我怎么就攤上這事”云埽” “怎么了亿汞?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長揪阿。 經(jīng)常有香客問我疗我,道長,這世上最難降的妖魔是什么南捂? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任吴裤,我火速辦了婚禮,結(jié)果婚禮上溺健,老公的妹妹穿的比我還像新娘麦牺。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布剖膳。 她就那樣靜靜地躺著魏颓,像睡著了一般。 火紅的嫁衣襯著肌膚如雪吱晒。 梳的紋絲不亂的頭發(fā)上琼开,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天,我揣著相機與錄音枕荞,去河邊找鬼。 笑死搞动,一個胖子當著我的面吹牛躏精,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播鹦肿,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼矗烛,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了箩溃?” 一聲冷哼從身側(cè)響起瞭吃,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎涣旨,沒想到半個月后歪架,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡霹陡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年和蚪,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片烹棉。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡攒霹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出浆洗,到底是詐尸還是另有隱情催束,我是刑警寧澤,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布伏社,位于F島的核電站抠刺,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏摘昌。R本人自食惡果不足惜矫付,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望第焰。 院中可真熱鬧买优,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至脂崔,卻和暖如春滤淳,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背砌左。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工脖咐, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人汇歹。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓屁擅,卻偏偏與公主長得像,于是被迫代替她去往敵國和親产弹。 傳聞我的和親對象是個殘疾皇子派歌,可洞房花燭夜當晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容