从我的服务器下载 *.csv

Wan*_*ter 3 csv http fileserver go

我是 Golang 新手,现在我正在编写解析某些页面的小应用程序。我得到索引页:

<form action="/" method='POST'>
    Enter credentials:<br>
    Login: <input type="text" name="login" >
    <br>
    Password: <input type="password" name="password" >
    <br>
    Search link:<br>
    <input type="text" name="link" >
    <br>
    <input type="submit" value="Submit">
 </form> 
Run Code Online (Sandbox Code Playgroud)

因此,单击“提交”按钮后,它会进入解析页面(使用 tebeca/selenium pkg),最后将数据写入 result.csv,如下所示

func writeToCSV(users []linkedinUser) {
data := users
enc := struct2csv.New()
rows, err := enc.Marshal(data)
if err != nil {
    fmt.Printf("ERROR marshaling file, %s", err)
}
file, err := os.Create("result.csv")
if err != nil {
    fmt.Printf("ERROR creating file, %s", err)
}
defer file.Close()

writer := csv.NewWriter(file)
defer writer.Flush()

for _, value := range rows {
    err := writer.Write(value)
    if err != nil {
        fmt.Printf("ERROR writing file, %s", err)
    }
}
Run Code Online (Sandbox Code Playgroud)

最后我在 /home/username/go/src/parser/parsertool/src/result.csv 中得到了 result.csv 文件

我的 main.go

func main() {
    r := mux.NewRouter()

    r.HandleFunc("/", indexHandler)
    http.Handle("/", r)

    err := http.ListenAndServe(":3000", nil) // setting listening port
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }


    func indexHandler(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("./front/index.html")
    badLoginT, _ := template.ParseFiles("./front/error.html")
    r.ParseForm()
    login := r.PostFormValue("login")
    password := r.PostFormValue("password")
    link := r.PostFormValue("link")
    if login != "" || password != "" {
        userCred := logincredentials.SetCredentials(login, password)
        if logincredentials.CheckCredentials(userCred) && link != "" {
            crawler.Crawl(link, login, password)
        } else {
            badLoginT.Execute(w, nil)
        }
    }

    t.Execute(w, nil)
}
Run Code Online (Sandbox Code Playgroud)

所以主要问题是: 有没有办法获得将 result.csv 下载到我的硬盘的链接?实施并不重要。可能是在writeToCSV()的末尾,当 result.csv 准备好时,会出现您可以选择文件保存位置的窗口,或者在获取 result.csv 后,会出现一些链接,如“点击下载”,点击后您可以请参阅下载窗口等。

我被困住了,真的不知道如何实现下载。我将不胜感激任何帮助。

edk*_*ked 5

在你的 Go 服务器上

func main() {
  r := mux.NewRouter()
  r.HandleFunc("/", indexHandler)
  http.Handle("/", r)
  err := http.ListenAndServe(":3000", nil) // setting listening port
  if err != nil {
    log.Fatal("ListenAndServe: ", err)
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    ...
    Openfile, err := os.Open(Filename)
    FileSize := strconv.FormatInt(FileStat.Size(), 10)
    FileContentType := http.DetectContentType(FileHeader)
    //Send the headers before sending the file
    writer.Header().Set("Content-Disposition", "attachment; filename="+Filename)
    writer.Header().Set("Content-Type", FileContentType)
    writer.Header().Set("Content-Length", FileSize)

    //Send the file
   io.Copy(w, Openfile) 
  }
Run Code Online (Sandbox Code Playgroud)

在你的客户端

由于要下载的文件是由服务器发送的,因此需要先使用js函数将表单发布到服务器。然后收到服务器的响应后,会直接通过同样的函数触发下载。

html

<form>
    Enter credentials:<br>
    Login: <input id="login" type="text" name="login" >
    <br>
    Password: <input id="password" type="password" name="password" >
    <br>
    Search link:<br>
    <input id="link" type="text" name="link" >
    <br>
    <input type="button" onclick="downloadFile()">
 </form> 
Run Code Online (Sandbox Code Playgroud)

在一个js文件中

function downloadFile() {
      var data = { 
       login: document.querySelector('#login').value,
       password: document.querySelector('#password').value,
       link: document.querySelector('#link').value
       }

      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        var a;
        if (xhttp.readyState === 4 && xhttp.status === 200) {
            a = document.createElement('a');
            a.href = window.URL.createObjectURL(xhttp.response);
            // Give to file the name you wish 
            a.download = "test-file.xls";
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
        }
    }
    }

    xhttp.open("POST", urlserver);
    xhttp.setRequestHeader("Content-Type", "application/json");
    // set responseType as blob for binary responses
    xhttp.responseType = 'blob';
    xhttp.send(JSON.stringify(data));
Run Code Online (Sandbox Code Playgroud)