如何通过http从golang服务器向flutter应用程序发送PDF文件数据

w46czmvw  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(146)

我想通过http将PDF文件数据从我的golang服务器发送到flutter应用程序。
为此,我创建了一个API,它以字节格式读取PDF文件,然后将其转换为字符串,并存储在Golang服务器中并发送到Flutter应用程序。
然后,我的flutter应用程序将字符串格式的数据转换为Uint8List格式,以便在flutter应用程序本身中存储和查看PDF。
但我无法观看。在那之后,我检查了我的文件下载位置,我发现所有的PDF文件在Flutter应用程序,我是downland查看那些是空白的。只有一个PDF我能够正常查看,因为它的大小是3k和其他PDF的大小是超过10 KB。
任何想法为什么我不能查看所有的PDF文件在Flutter?

http中是否有任何限制发送特定大小的数据?
查看PDF文件在flutter应用程序,我从我的golang服务器下载。
我的Golang代码如下:

file, err := os.Open(filePath)
    if err != nil {
        ctx.JSON(http.StatusOK, gin.H{
            "status": false,
            "error":  err,
        })
    }
    defer file.Close()

    // Get the file size
    stat, err := file.Stat()
    if err != nil {
        ctx.JSON(http.StatusOK, gin.H{
            "status": false,
            "error":  err,
        })
    }

    // Read the file into a byte slice
    bs := make([]byte, stat.Size())
    _, err = bufio.NewReader(file).Read(bs)

    if err != nil && err != io.EOF {
        ctx.JSON(http.StatusOK, gin.H{
            "status": false,
            "error":  err,
        })
    } else {
        ctx.JSON(http.StatusOK, gin.H{
            "status":    true,
            "bytesdata": string(bs),
        })
    }

Flutter代码如下:

final bytesdata = data['bytesdata'];
final List<int> codeUnits = bytesdata.codeUnits;
final Uint8List fileData = Uint8List.fromList(codeUnits);
var dir1 = await getExternalStorageDirectory();
if (dir1 != null) {
   File file = File("${dir1.path}/$fileNameToView");
   await file.writeAsBytes(fileData, flush: true);
   _redirectToPDFPage(file.readAsBytesSync(), fileList[index]["filename"]);
}
u91tlkcl

u91tlkcl1#

试试这个代码可能适合你

package main

import (
    "io/ioutil"
    "net/http"
)

func handlePDFRequest(w http.ResponseWriter, r *http.Request) {
    pdfData, err := ioutil.ReadFile("path/to/your/pdf/file.pdf")
    if err != nil {
        http.Error(w, "Failed to read PDF file", http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/pdf")
    w.Header().Set("Content-Disposition", "attachment; filename=\"file.pdf\"")

    _, err = w.Write(pdfData)
    if err != nil {
        http.Error(w, "Failed to send PDF file", http.StatusInternalServerError)
        return
    }
}

func main() {
    http.HandleFunc("/pdf", handlePDFRequest)
    http.ListenAndServe(":8080", nil)
}

相关问题