首页 > 其他分享 >Go - Uploading a File to a Web Application

Go - Uploading a File to a Web Application

时间:2023-10-17 15:15:06浏览次数:36  
标签:Web http err form Uploading upload application file Go

Problem: You want to upload a file to a web application.

 

Solution: Use the net/http package to create a web application and the io package to read the file.

 

Uploading files is commonly done through HTML forms. You learned that HTML forms have an enctype attribute that specifies the format of the form data. By default, the enctype is set to application/x - www - form - urlencoded . This means that the form data is encoded as a query string. However, if you set the enctype to multipart/form - data , the form data will be encoded as a MIME message. This is the format you need to upload files. 

Here’s an example. You will create a web application that allows users to upload a file. The web application will display the filename and the file size. The web application will also save the file to the local filesystem:

func   main ()   { 
      http . HandleFunc ( "/upload" ,   upload ) 
      http . ListenAndServe ( ":8000" ,   nil ) 
} 

func   upload ( w   http . ResponseWriter ,   r   * http . Request )   { 
      file ,   fileHeader ,   err   :=   r . FormFile ( "uploadfile" ) 
      if   err   !=   nil   { 
          fmt . Println ( err ) 
          return 
      } 
      defer   file . Close () 
      fmt . Fprintf ( w ,   "%v" ,   fileHeader . Header ) 
      f ,   err   :=   os . OpenFile ( "./uploaded/" + fileHeader . Filename ,  os . O_WRONLY | os . O_CREATE ,   0666 ) 
      if   err   !=   nil   { 
          fmt . Println ( err ) 
          return 
      } 
      defer   f . Close () 
      io . Copy ( f ,   file ) 
}

The first thing you need to do is to get the file from the HTML form. You can do this using the FormFile method. The FormFile method takes the name of the file input element as its argument and returns two values and an error. The first value is the file, an io.ReadCloser , and the second value is the file metadata, a multipart.FileHeader .

Using the file header, get the filename and then create a new file. Then use the io.Copy function to copy the file from the io.ReadCloser to the new file. 

To test this, use curl to post a file to the server form. The syntax for curl is to use the - F (form) option, which will add enctype="multipart/form - data" to the request. The argument to this option is a string with the name of the file form field ( uploadfile ), followed by = and then @ followed by the path to the file to upload:

$  curl  - F  "[email protected]"  http://localhost:8000/upload

Once you run this command, you should see a file lenna.png created in the .uploaded directory.

 

标签:Web,http,err,form,Uploading,upload,application,file,Go
From: https://www.cnblogs.com/zhangzhihui/p/17769720.html

相关文章

  • 一图看懂CodeArts Governance 三大特性,带你玩转开源治理服务
    华为云开源治理服务CodeArtsGovernance是针对软件研发提供的一站式开源软件治理服务,凝聚华为在开源治理上的优秀实践经验,提供开源软件元数据及软件成分分析、恶意代码检测等能力,从合法合规、网络安全、供应安全等维度消减开源软件使用风险,助力企业更加安全、高效地使用开源软件。......
  • CF841B Godsend
    首先偶数是可以忽略的,因为拿了不影响奇偶性,并且序列中只有偶数或没有数均为先手必败,所以两人拿多少也都没有关系。考虑奇数的个数,如果有奇数个奇数,先手直接拿完获得胜利。否则先手可以先拿奇数个奇数,剩下仍然有奇数个奇数,而后手只能拿偶数个奇数,这就保证了下一轮的奇数个数变成......
  • python链接mongodb的问题
    python链接mongodb需要指定数据库importpymongomonclient=pymongo.MongoClient("mongodb://用户名:密码@192.168.10.200:27017/数据库名")mondb=monclient["数据库名"]moncol=mondb["表名"]网上很多资料都没有指定数据库名,导致后续操作提示没有权限......
  • Go - Handling HTML Forms
    Problem: YouwanttoprocessdatasubmittedfromHTMLforms.Solution: UsetheFormfieldofhttp.RequestortheFormValuemethodtoaccessthedatasubmittedfromHTMLforms. AtypicalHTMLformoftenlookslikethis:<formaction="/proc......
  • Util应用框架Web Api开发环境搭建
    要使用Util应用框架开发项目,首先需要搭建合适的开发环境.迈出第一步,对于很多.Net新人可能并不简单.如果你对.Net环境并不熟悉,请尽量按照本文档进行操作.操作系统请安装Windows10以上版本操作系统.你也可以使用MAC操作系统,但需要自行解决开发环境问题.安装VisualSt......
  • javaWeb-MVC 和三层架构(非详解)
    1.MVC模式MVC结构:MVC是一种分层开发的模式其中1.M:Model,业务模型,处理业务2.V:View,视图,界面展示3.C:Controller,控制器,处理请求,调用模型和视图 下面是一张展示流程控制图MVC的好处:1.职责单一,互不影响2.有利于分工协作3.利于维护,利于组件重用2.三层架构1表现层2.业务逻辑......
  • javaweb-jsp脚本总结笔记
    1什么是JSPjsp又叫JavaserveltPage这门技术最大的特点就是,写jsp就像是再写html但是不仅可以写静态页面,而且可以内置Java代码写出动态页面,也就是说可以为用户提供动态数据。总的来说jsp=java+HTML2.JSP快速入门2.1提供对应的驱动包2.1创建对应jsp文件2.2写对应代码......
  • Docker安装Mongodb
    一、宿主机创建目录,存放mongodb配置信息、数据信息mkdir-p/usr/local/mymongo/conf二、参考官方配置文档,配置mongod.conf#在上面的conf目录下,创建mongod.confsystemLog:destination:filepath:/var/log/mongodb/mongod.loglogAppend:truestorage:dbPath:......
  • go 包总结
    (3).总结:编译语言,不像其它脚本语言(边解析边执行).go中所有的代码要进行编译.必须要有一个入口函数,在这个函数中去执行代码.int在赋值的时候没有函数入口,就只是在一个全局的区域里面.任何执行的语句,都要在函数以内执行.而varAgeint=10表示在编译的时候,就直接声明变量再......
  • TypeError: Polygon.__init__() takes 2 positional arguments but 3 were given
    《程序员数学:用Python学透线性代数和微积分》第3.5章,源码bug修正。报错信息:wang@wanggongdeMacBook-AirpythonTest%/usr/local/bin/python3/Users/wang/Documents/VSCode/pythonTest/chapter3/chapter3.pyTraceback(mostrecentcalllast):File"/Users/wang/Document......