ZBLOG

go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { http.HandleFunc("/upload", uploadHandler) err := http.ListenAndServe(":8888", nil) if err != nil { fmt.Println("Server error:", err) } } func uploadHandler(w http.Re...

您需要对uploadHandler函数进行修改,以便在文件和信息保存成功后返回成功的响应。以下是修改后的代码示例:

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "mime/multipart"
  6. "net/http"
  7. )
  8. func main() {
  9. http.HandleFunc("/upload", uploadHandler)
  10. err := http.ListenAndServe(":8888", nil)
  11. if err != nil {
  12. fmt.Println("Server error:", err)
  13. }
  14. }
  15. func uploadHandler(w http.ResponseWriter, r *http.Request) {
  16. if r.Method != "POST" {
  17. w.WriteHeader(http.StatusMethodNotAllowed)
  18. return
  19. }
  20. file, handler, err := r.FormFile("file")
  21. if err != nil {
  22. w.WriteHeader(http.StatusBadRequest)
  23. fmt.Fprint(w, "Failed to retrieve file from request.")
  24. return
  25. }
  26. defer file.Close()
  27. info := r.FormValue("info")
  28. saveFile(file, handler.Filename)
  29. saveInfo(info)
  30. response := struct {
  31. Status int `json:"status"`
  32. Message string `json:"message"`
  33. }{
  34. Status: http.StatusOK,
  35. Message: "success",
  36. }
  37. w.Header().Set("Content-Type", "application/json")
  38. w.WriteHeader(http.StatusOK)
  39. json.NewEncoder(w).Encode(response)
  40. }
  41. func saveFile(file multipart.File, filename string) {
  42. data, err := ioutil.ReadAll(file)
  43. if err != nil {
  44. fmt.Println("Failed to read file data:", err)
  45. return
  46. }
  47. // 将文件保存在当前目录下
  48. filePath := "./" + filename
  49. err = ioutil.WriteFile(filePath, data, 0644)
  50. if err != nil {
  51. fmt.Println("Failed to save file:", err)
  52. return
  53. }
  54. fmt.Println("File saved:", filePath)
  55. }
  56. func saveInfo(info string) {
  57. infoFilePath := "./info.txt"
  58. err := ioutil.WriteFile(infoFilePath, []byte(info), 0644)
  59. if err != nil {
  60. fmt.Println("Failed to save info:", err)
  61. return
  62. }
  63. fmt.Println("Info saved:", infoFilePath)
  64. }

以上代码在文件和信息保存成功后,将返回一个状态码为200、消息为”success”的JSON响应。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=16676

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?