从golang服务器下载浏览器中的压缩文件

时间:2014-02-11 03:36:51

标签: javascript angularjs go zip

我正在尝试从Go网络服务器下载压缩文件。我已成功压缩文件,可以从服务器的目录中解压缩。我遇到的问题是提供文件并使用Javascript下载。

以下是我的代码概述:

1)向服务器发出请求,该服务器从另一个端点检索数据

2)根据用户想要的文件类型(CSV(setupCSVRows函数)或JSON)构造返回的数据

3)将缓冲区中的字节写入文件并返回文件的地址

4)当用户点击链接时,使用文件地址发出http get请求,并在新窗口中打开内容进行下载

每当我尝试解压缩文件时,我都会收到错误:存档文件不完整(使用Unarchiver程序),Mac上的默认存档实用程序会显示一个简短的加载屏幕然后关闭。

Go Code:

func ExportData(writer http.ResponseWriter, req *http.Request, session sessions.Session) (int, string) {

headers := HeaderCreation{
    OriginalRequest: req,
    Session:         session,
}

qs := req.URL.Query()

if len(qs["collectionID"]) != 1 {
    return 400, "ERROR: Must submit one collectionID in query string"
}
if len(qs["fileType"]) != 1 {
    return 400, "ERROR: Must submit one fileType in query string"
}

collID := qs["collectionID"][0]
fileType := qs["fileType"][0]

url := "http://" + config.Data.Address + "/api/" + collID
response, err := httpClient.DoSystemRequest("GET", url, nil, headers)

if err != nil {
    return 500, "ERROR: Could not resolve DataURL/api" + err.Error()
} else {
    contents, err := ioutil.ReadAll(response.Body)
    response.Body.Close()

    if err != nil {
        return 400, "ERROR: Response from Platform unreadable"
    }

    buf := new(bytes.Buffer)

    w := zip.NewWriter(buf)

    file, err := w.Create(collID + "." + fileType)
    if err != nil {
        return 400, "ERROR: Unable to create zip file with name of: " + collID + " and type of: " + fileType + "; " + err.Error()
    }

    switch fileType {
    case "csv":

        rows, err := setupCSVRows(contents)

        if err != nil {
            return 400, err.Error()
        }

        _, err = file.Write(rows)
        if err != nil {
            return 400, "Unable to write CSV to zip file; " + err.Error()
        }
    case "json":
        _, err := file.Write(contents)
        if err != nil {
            return 400, err.Error()
        }
    } // end switch

    err = w.Close()
    if err != nil {
        return 400, "ERROR: Unable to close zip file writer; " + err.Error()
    }

    //create fileName based on collectionID and current time
    fileAddress := collID + strconv.FormatInt(time.Now().Unix(), 10)

    //write the zipped file to the disk
    ioutil.WriteFile(fileAddress + ".zip", buf.Bytes(), 0777)

    return 200, fileAddress
} //end else
}

func ReturnFile(writer http.ResponseWriter, req *http.Request) {
queries := req.URL.Query()
fullFileName := queries["fullFileName"][0]
http.ServeFile(writer, req, fullFileName)
//delete file from server once it has been served
//defer os.Remove(fullFileName)
}

func setupCSVRows(contents []byte) ([]byte, error) {
//unmarshal into interface because we don't know json structure in advance
var collArr interface{}
jsonErr := json.Unmarshal(contents, &collArr)

if jsonErr != nil {
    return nil, errors.New("ERROR: Unable to parse JSON")
}

//had to do some weird stuff here, not sure if it's the best method
s := reflect.ValueOf(collArr)
var rows bytes.Buffer
var headers []string

for i := 0; i < s.Len(); i++ {
    var row []string
    m := s.Index(i).Interface()

    m2 := m.(map[string]interface{})

    for k, v := range m2 {

        if i == 0 {
            if k != "item_id" {
                headers = append(headers, k)
            }
        }
        if k != "item_id" {
            row = append(row, v.(string))
        }
    }

    if i == 0 {
        headersString := strings.Join(headers, ",")
        rows.WriteString(headersString + "\n")
    }
    rowsString := strings.Join(row, ",")
    rows.WriteString(rowsString + "\n")
}

return rows.Bytes(), nil
}

Javascript代码:

$scope.exportCollection = function(fileType) {
    $scope.exporting = true;
    $scope.complete = false;

    $http.get('/api/batch/export?collectionID=' + $scope.currentCollection.collectionID + '&fileType=' + fileType.toLowerCase()).success(function(data){
    $scope.fileAddress = data;

    }).error(function(err) {
  console.log(err);
    });

};

$scope.downloadFile = function() {
    $http.get('/api/batch/export/files?fullFileName=' + $scope.fileAddress + ".zip")
      .success(function(data) {
        console.log(data);

    //window.open("data:application/zip;base64," + content);
    //var content = "data:text/plain;charset=x-user-defined," + data;
    var content = "data:application/zip;charset=utf-8," + data;
    //var content = "data:application/octet-stream;charset=utf-8" + data;
    //var content = "data:application/x-zip-compressed;base64," + data;
    //var content = "data:application/x-zip;charset=utf-8," + data;
    // var content = "data:application/x-zip-compressed;base64," + data;
    window.open(content);
  })
  .error(function(err) {
    console.log(err);
  })
}

正如您所看到的,我尝试了许多不同的URI方案来下载文件,但没有任何工作。

我是否需要在服务器端设置MIME类型?

非常感谢任何帮助。如果我需要提供更多详细信息,请与我们联系。

2 个答案:

答案 0 :(得分:5)

我无法评论(新用户) - 但是在命名文件方面,只需在服务之前设置标题(使用ServeContent,但在这里应该可以互换):

 func serveFile(w http.ResponseWriter, r *http.Request){
    data, err := ioutil.ReadFile("path/to/file/and/file+ext")
    if(err != nil){
        log.Fatal(err)
    }
    w.Header().Set("Content-Type", "application/octet-stream")
    w.Header().Set("Content-Disposition", "attachment; filename=" + "fileName.here")
    w.Header().Set("Content-Transfer-Encoding", "binary")
    w.Header().Set("Expires", "0")
    http.ServeContent(w, r, "path/to/file/and/file+ext", time.Now(), bytes.NewReader(data))

}

答案 1 :(得分:2)

我最终走的路线略有不同。现在,我在响应头上设置MIME类型,并创建一个指向该文件的链接。

转到代码:

func ReturnFile(writer http.ResponseWriter, req *http.Request) {
queries := req.URL.Query()
fullFileName := queries["fullFileName"][0]

writer.Header().Set("Content-type", "application/zip")
http.ServeFile(writer, req, fullFileName)
//delete file from server once it has been served
defer os.Remove(fullFileName)
}

Angular UI代码:

<a ng-show="complete" href="/api/batch/export/files?fullFileName={{fileAddress}}">Download {{currentCollection.name}}</a>

这会自动触发下载,并且zip文件不再损坏。