Golang新手求助 - 上传PDF文件时遇到iframe错误
Golang新手求助 - 上传PDF文件时遇到iframe错误 大家好,我最近刚开始接触Go,并且已经成为了它的忠实粉丝。
目前我正在开发一个Web应用程序,用户需要能够上传PDF文件,并且这些文件可以通过浏览器(PDF查看器)打开。
我遇到的问题:
如果我尝试使用 ioutil.TempFile(),文件会损坏,我无法通过浏览器和我本地安装的PDF阅读器打开它。如果我尝试捕获文件,使用 ioutil.ReadAll() 并通过 ioutil.WriteFile() 将所有数据写入一个新文件,那么文件本身是完好的,但我仍然无法通过我的网站打开它。
有人能告诉我,如何访问 multipart.file 的临时文件信息吗?
if r.Method == http.MethodPost {
r.ParseMultipartForm(maxUploadSize)
file, handler, err := r.FormFile("myFile")
if err != nil {
utils.InternalServerError(w)
return
}
defer file.Close()
data, err2 := ioutil.ReadAll(file)
if err2 != nil {
utils.LoggingWarningFile(err2.Error())
return
}
path = temp + "\\" + itemname + fileExt
err2 = ioutil.WriteFile(path, data, 0777)
if err2 != nil {
fmt.Println(err2)
return
}
}
对于任何提示或解决方案,我都会非常感激。 谢谢
更多关于Golang新手求助 - 上传PDF文件时遇到iframe错误的实战教程也可以访问 https://www.itying.com/category-94-b0.html
尽管一路上遇到了一些困难,但最终我找到了一个方法来获取并存储文件。
data, err2 := ioutil.ReadAll(file)
utils.CheckError(err2)
err2 = ioutil.WriteFile(path,data,0644)
utils.CheckError(err2)
在这个小小的成就之后,我尝试用 PDFViewer 打开它。我仍然对自己的解决方案不太满意,但目前这是一个不错的变通方法:
f, err := os.Open(path)
utils.CheckError(err)
defer f.Close()
w.Header().Set("Content-type", "application/pdf")
if _, err := io.Copy(w, f); err != nil {
utils.LoggingErrorFile(err.Error())
w.WriteHeader(500)
}
也许我能帮到其他人。
更多关于Golang新手求助 - 上传PDF文件时遇到iframe错误的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
根据你的描述,问题可能出现在文件路径处理或HTTP响应头设置上。以下是修复后的代码示例:
package main
import (
"io"
"net/http"
"os"
"path/filepath"
)
const maxUploadSize = 10 * 1024 * 1024 // 10MB
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// 限制请求体大小
r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
// 解析multipart表单
err := r.ParseMultipartForm(maxUploadSize)
if err != nil {
http.Error(w, "File too large", http.StatusBadRequest)
return
}
// 获取上传的文件
file, handler, err := r.FormFile("myFile")
if err != nil {
http.Error(w, "Invalid file", http.StatusBadRequest)
return
}
defer file.Close()
// 验证文件类型
buff := make([]byte, 512)
_, err = file.Read(buff)
if err != nil {
http.Error(w, "File read error", http.StatusInternalServerError)
return
}
filetype := http.DetectContentType(buff)
if filetype != "application/pdf" {
http.Error(w, "Invalid file type", http.StatusBadRequest)
return
}
// 重置文件指针
_, err = file.Seek(0, io.SeekStart)
if err != nil {
http.Error(w, "File seek error", http.StatusInternalServerError)
return
}
// 创建目标文件
tempDir := "./uploads"
os.MkdirAll(tempDir, 0755)
filePath := filepath.Join(tempDir, handler.Filename)
dst, err := os.Create(filePath)
if err != nil {
http.Error(w, "Failed to create file", http.StatusInternalServerError)
return
}
defer dst.Close()
// 复制文件内容
_, err = io.Copy(dst, file)
if err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError)
return
}
// 设置正确的响应头
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition", "inline; filename=\""+handler.Filename+"\"")
// 读取并返回文件内容
http.ServeFile(w, r, filePath)
}
func main() {
http.HandleFunc("/upload", uploadHandler)
http.ListenAndServe(":8080", nil)
}
对于在iframe中显示PDF,需要确保服务器正确设置Content-Type头:
func viewPDFHandler(w http.ResponseWriter, r *http.Request) {
filePath := "./uploads/sample.pdf"
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition", "inline; filename=\"document.pdf\"")
http.ServeFile(w, r, filePath)
}
HTML部分需要正确配置iframe:
<iframe src="/view-pdf" width="100%" height="600px"></iframe>
关键点:
- 使用
io.Copy()直接复制文件流,避免内存问题 - 设置正确的Content-Type头为
application/pdf - 使用
Content-Disposition: inline让浏览器内联显示 - 验证文件类型确保上传的是有效的PDF文件
- 使用
http.ServeFile()高效服务静态文件
如果PDF仍然无法显示,检查浏览器控制台是否有CORS或MIME类型错误。

