doudou0612 2016-06-18 02:45
浏览 165

强制浏览器从Golang下载返回数据

I have a Go server that serves endpoints of an api. One of the endpoints creates an mp3 file and returns either the path of the converted file or all the bytes of the file. I am looking for one of two solutions.

The first solution would be to allow local file access for the 'href'. I have the output file string "/tmp/audio-hash123.mp3" returned from the Go server after it has done it's thing. The problem is that whenever I pass that to the 'href' to trigger the file download, it treats it as an absolute path such as "www.example.com/tmp/audio-hash123.mp3" instead of just allowing local access to the file. I have the converted audio file available locally but my tmp directory is obviously not externally accessible so this fails every time. Is this even possible?

The second solution would be for the client to allow for a triggered download based on the actual audio file returned from the server, not just the file path. I can't think of any way this is possible based on the fact that the html 'download' attribute is based on the path to the file to be downloaded. Is there a way to force a file download based on returning from the server the actual audio file?

Below is a small portion of the Go server that sends back either the file path or the actual audio file (in a byte array):

if ReturnFilePath == true {
    //return the filepath for webpage to download
    request.Send(outputFile)
} else {
    //return the audio file
    //get mime type
    mimeType := GetMime(filepath)
    if mimeType != "" {
        req.Ctx.Response.Header.Set("Content-Type", mimeType)
    }

    //open image
    file, err := os.Open(filepath)
    if err != nil {
        req.Send(err.Error())
        return
    }

    //get bytes of image
    bytes, err := ioutil.ReadAll(file)
    if err != nil {
        req.Send(err.Error())
        return
    }

    req.Send(bytes)
}

With the data returned, I will facilitate the download in JavaScript. But, I need help in figuring out how to accomplish this. Any help is appreciated.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 Pwm双极模式H桥驱动控制电机
    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题