Go编程新手求助:如何将第三方API返回的PDF文件上传至文件夹
How to Save a PDF from an API Response to a Local File in Go
Hey there! I totally get how frustrating it can be stuck on this for days—let's get this sorted out for you right away. You've already nailed the part of fetching the PDF from the third-party API; now we just need to write that response body to a local file.
First, let's fix up your existing code with proper error handling (super important in Go!) and add the file-saving logic. Here's a complete, working example:
package main import ( "fmt" "io" "net/http" "os" ) func main() { url := "https://api.xyz.com/v3/files/fcc280cf620204d4bb5dbd6a8cbbbb8fea1a20fc" client := &http.Client{} // Create the GET request req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } req.Header.Set("Content-Type", "application/json") req.SetBasicAuth("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "") // Execute the request resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // First, check if the API returned a successful response if resp.StatusCode != http.StatusOK { fmt.Printf("API returned non-success status: %d %s\n", resp.StatusCode, resp.Status) return } // Create a local file to save the PDF outFile, err := os.Create("downloaded.pdf") if err != nil { fmt.Printf("Failed to create file: %v\n", err) return } defer outFile.Close() // Copy the response body to the file _, err = io.Copy(outFile, resp.Body) if err != nil { fmt.Printf("Failed to save PDF to file: %v\n", err) return } fmt.Println("PDF saved successfully as downloaded.pdf!") }
Let me break down what's new here:
- Proper Error Handling: We're now checking every possible error point (request creation, request execution, file creation, copy operation) and printing meaningful messages instead of generic "Failed" or "ERROR" alerts.
- Response Status Check: Before saving, we verify that the API returned a
200 OKstatus—this ensures we're not trying to save an error page (like a 404 or 500) as a PDF. - File Creation:
os.Create("downloaded.pdf")creates a new file (or overwrites an existing one with the same name) in your current working directory. You can tweak the path/filename to fit your needs (e.g.,"./documents/invoice.pdf"). - Copying the PDF Content:
io.Copyefficiently streams data from the API response body (resp.Body, anio.Reader) to the file (outFile, anio.Writer). This avoids loading the entire PDF into memory, which is perfect for larger files.
A couple of extra tips:
- If you want to confirm the file saved correctly, you can add a check for the file size after copying, or open it manually to verify it's a valid PDF.
- If the API includes a filename in the
Content-Dispositionheader, you can parse that value to use the original filename instead of hardcoding "downloaded.pdf".
内容的提问来源于stack exchange,提问作者devtraining
相关产品推荐
相关产品推荐

