网站建设资讯

NEWS

网站建设资讯

go语言客户端上传文件,go 引用文件

golang怎么通过数据流直接生成excel上传至oss

import java.io.*; import jxl.*; … … … … try { //构建Workbook对象, 只读Workbook对象 //直接从本地文件创建Workbook //从输入流创建Workbook InputStream is = new FileInputStream(sourcefile); jxl.Workbook rwb = Workbook.getWorkbook(is); } catch (Exception e) { e.printStackTrace(); } 一旦创建了Workbook,我们就可以通过它来访问Excel Sheet(术语:工作表)。参考下面的代码片段: //获取第一张Sheet表 Sheet rs = rwb.getSheet(0); 我们既可能通过Sheet的名称来访问它,也可以通过下标来访问它。如果通过下标来访问的话,要注意的一点是下标从0开始,就像数组一样。 一旦得到了Sheet,我们就可以通过它来访问Excel Cell(术语:单元格)。参考下面的代码片段: //获取第一行,第一列的值 Cell c00 = rs.getCell(0, 0); String strc00 = c00.getContents(); //获取第一行,第二列的值 Cell c10 = rs.getCell(1, 0); String strc10 = c10.getContents(); //获取第二行,第二列的值 Cell c11 = rs.getCell(1, 1); String strc11 = c11.getContents(); System.out.println("Cell(0, 0)" + " value : " + strc00 + "; type : " + c00.getType()); System.out.println("Cell(1, 0)" + " value : " + strc10 + "; type : " + c10.getType()); System.out.println("Cell(1, 1)" + " value : " + strc11 + "; type : " + c11.getType()); 如果仅仅是取得Cell的值,我们可以方便地通过getContents()方法,它可以将任何类型的Cell值都作为一个字符串返回。示例代码中Cell(0, 0)是文本型,Cell(1, 0)是数字型,Cell(1,1)是日期型,通过getContents(),三种类型的返回值都是字符型。 如果有需要知道Cell内容的确切类型,API也提供了一系列的方法。参考下面的代码片段: String strc00 = null; double strc10 = 0.00; Date strc11 = null; Cell c00 = rs.getCell(0, 0); Cell c10 = rs.getCell(1, 0); Cell c11 = rs.getCell(1, 1); if(c00.getType() == CellType.LABEL) { LabelCell labelc00 = (LabelCell)c00; strc00 = labelc00.getString(); } if(c10.getType() == CellType.NUMBER) { NmberCell numc10 = (NumberCell)c10; strc10 = numc10.getValue(); } if(c11.getType() == CellType.DATE) { DateCell datec11 = (DateCell)c11; strc11 = datec11.getDate(); } System.out.println("Cell(0, 0)" + " value : " + strc00 + "; type : " + c00.getType()); System.out.println("Cell(1, 0)" + " value : " + strc10 + "; type : " + c10.getType()); System.out.println("Cell(1, 1)" + " value : " + strc11 + "; type : " + c11.getType()); 在得到Cell对象后,通过getType()方法可以获得该单元格的类型,然后与API提供的基本类型相匹配,强制转换成相应的类型,最后调用相应的取值方法getXXX(),就可以得到确定类型的值。API提供了以下基本类型,与Excel的数据格式相对应,如下图所示: 每种类型的具体意义,请参见Java Excel API Document。 当你完成对Excel电子表格数据的处理后,一定要使用close()方法来关闭先前创建的对象,以释放读取数据表的过程中所占用的内存空间,在读取大量数据时显得尤为重要。参考如下代码片段: //操作完成时,关闭对象,释放占用的内存空间 rwb.close(); Java Excel API提供了许多访问Excel数据表的方法,在这里我只简要地介绍几个常用的方法,其它的方法请参考附录中的Java Excel API Document。 • Workbook类提供的方法 1. int getNumberOfSheets() 获得工作薄(Workbook)中工作表(Sheet)的个数,示例: jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile)); int sheets = rwb.getNumberOfSheets(); 2. Sheet[] getSheets() 返回工作薄(Workbook)中工作表(Sheet)对象数组,示例: jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile)); Sheet[] sheets = rwb.getSheets(); 3. String getVersion() 返回正在使用的API的版本号,好像是没什么太大的作用。 jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile)); String apiVersion = rwb.getVersion(); • Sheet接口提供的方法 1. String getName() 获取Sheet的名称,示例: jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile)); jxl.Sheet rs = rwb.getSheet(0); String sheetName = rs.getName(); 2. int getColumns() 获取Sheet表中所包含的总列数,示例: jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile)); jxl.Sheet rs = rwb.getSheet(0); int rsColumns = rs.getColumns(); 3. Cell[] getColumn(int column) 获取某一列的所有单元格,返回的是单元格对象数组,示例: jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile)); jxl.Sheet rs = rwb.getSheet(0); Cell[] cell = rs.getColumn(0); 4. int getRows() 获取Sheet表中所包含的总行数,示例: jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile)); jxl.Sheet rs = rwb.getSheet(0); int rsRows = rs.getRows(); 5. Cell[] getRow(int row) 获取某一行的所有单元格,返回的是单元格对象数组,示例子: jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile)); jxl.Sheet rs = rwb.getSheet(0); Cell[] cell = rs.getRow(0); 6. Cell getCell(int column, int row) 获取指定单元格的对象引用,需要注意的是它的两个参数,第一个是列数,第二个是行数,这与通常的行、列组合有些不同。 jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile)); jxl.Sheet rs = rwb.getSheet(0); Cell cell = rs.getCell(0, 0); 生成新的Excel工作薄 下面的代码主要是向大家介绍如何生成简单的Excel工作表,在这里单元格的内容是不带任何修饰的(如:字体,颜色等等),所有的内容都作为字符串写入。(完整代码见ExcelWriting.java) 与读取Excel工作表相似,首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象,这里要注意的是,只能通过API提供的工厂方法来创建Workbook,而不能使用WritableWorkbook的构造函数,因为类WritableWorkbook的构造函数为protected类型。示例代码片段如下: import java.io.*; import jxl.*; import jxl.write.*; … … … … try { //构建Workbook对象, 只读Workbook对象 //Method 1:创建可写入的Excel工作薄 jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File(targetfile)); //Method 2:将WritableWorkbook直接写入到输出流 /* OutputStream os = new FileOutputStream(targetfile); jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(os); */ } catch (Exception e) { e.printStackTrace(); } API提供了两种方式来处理可写入的输出流,一种是直接生成本地文件,如果文件名不带全路径的话,缺省的文件会定位在当前目录,如果文件名带有全路径的话,则生成的Excel文件则会定位在相应的目录;另外一种是将Excel对象直接写入到输出流,例如:用户通过浏览器来访问Web服务器,如果HTTP头设置正确的话,浏览器自动调用客户端的Excel应用程序,来显示动态生成的Excel电子表格。 接下来就是要创建工作表,创建工作表的方法与创建工作薄的方法几乎一样,同样是通过工厂模式方法获得相应的对象,该方法需要两个参数,一个是工作表的名称,另一个是工作表在工作薄中的位置,参考下面的代码片段: //创建Excel工作表 jxl.write.WritableSheet ws = wwb.createSheet("Test Sheet 1", 0); "这锅也支好了,材料也准备齐全了,可以开始下锅了!",现在要做的只是实例化API所提供的Excel基本数据类型,并将它们添加到工作表中就可以了,参考下面的代码片段: //1.添加Label对象 jxl.write.Label labelC = new jxl.write.Label(0, 0, "This is a Label cell"); ws.addCell(labelC); //添加带有字型Formatting的对象 jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES, 18, WritableFont.BOLD, true); jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf); jxl.write.Label labelCF = new jxl.write.Label(1, 0, "This is a Label Cell", wcfF); ws.addCell(labelCF); //添加带有字体颜色Formatting的对象 jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.RED); jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc); jxl.write.Label labelCFC = new jxl.write.Label(1, 0, "This is a Label Cell", wcfFC); ws.addCell(labelCF); //2.添加Number对象 jxl.write.Number labelN = new jxl.write.Number(0, 1, 3.1415926); ws.addCell(labelN); //添加带有formatting的Number对象 jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##"); jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf); jxl.write.Number labelNF = new jxl.write.Number(1, 1, 3.1415926, wcfN); ws.addCell(labelNF); //3.添加Boolean对象 jxl.write.Boolean labelB = new jxl.write.Boolean(0, 2, false); ws.addCell(labelB); //4.添加DateTime对象 jxl.write.DateTime labelDT = new jxl.write.DateTime(0, 3, new java.util.Date()); ws.addCell(labelDT); //添加带有formatting的DateFormat对象 jxl.write.DateFormat df = new jxl.write.DateFormat("dd MM yyyy hh:mm:ss"); jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df); jxl.write.DateTime labelDTF = new jxl.write.DateTime(1, 3, new java.util.Date(), wcfDF); ws.addCell(labelDTF); 这里有两点大家要引起大家的注意。第一点,在构造单元格时,单元格在工作表中的位置就已经确定了。一旦创建后,单元格的位置是不能够变更的,尽管单元格的内容是可以改变的。第二点,单元格的定位是按照下面这样的规律(column, row),而且下标都是从0开始,例如,A1被存储在(0, 0),B1被存储在(1, 0)。 最后,不要忘记关闭打开的Excel工作薄对象,以释放占用的内存,参见下面的代码片段: //写入Exel工作表 wwb.write(); //关闭Excel工作薄对象 wwb.close(); 这可能与读取Excel文件的操作有少少不同,在关闭Excel对象之前,你必须要先调用write()方法,因为先前的操作都是存储在缓存中的,所以要通过该方法将操作的内容保存在文件中。如果你先关闭了Excel对象,那么只能得到一张空的工作薄了。 拷贝、更新Excel工作薄 接下来简要介绍一下如何更新一个已经存在的工作薄,主要是下面二步操作,第一步是构造只读的Excel工作薄,第二步是利用已经创建的Excel工作薄创建新的可写入的Excel工作薄,参考下面的代码片段:(完整代码见ExcelModifying.java) //创建只读的Excel工作薄的对象 jxl.Workbook rw = jxl.Workbook.getWorkbook(new File(sourcefile)); //创建可写入的Excel工作薄对象 jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File(targetfile), rw); //读取第一张工作表 jxl.write.WritableSheet ws = wwb.getSheet(0); //获得第一个单元格对象 jxl.write.WritableCell wc = ws.getWritableCell(0, 0); //判断单元格的类型, 做出相应的转化 if(wc.getType() == CellType.LABEL) { Label l = (Label)wc; l.setString("The value has been modified."); } //写入Excel对象 wwb.write(); //关闭可写入的Excel对象 wwb.close(); //关闭只读的Excel对象 rw.close(); 之所以使用这种方式构建Excel对象,完全是因为效率的原因,因为上面的示例才是API的主要应用。为了提高性能,在读取工作表时,与数据相关的一些输出信息,所有的格式信息,如:字体、颜色等等,是不被处理的,因为我们的目的是获得行数据的值,既使没有了修饰,也不会对行数据的值产生什么影响。唯一的不利之处就是,在内存中会同时保存两个同样的工作表,这样当工作表体积比较大时,会占用相当大的内存,但现在好像内存的大小并不是什么关键因素了。 一旦获得了可写入的工作表对象,我们就可以对单元格对象进行更新的操作了,在这里我们不必调用API提供的add()方法,因为单元格已经于工作表当中,所以我们只需要调用相应的setXXX()方法,就可以完成更新的操作了。 尽单元格原有的格式化修饰是不能去掉的,我们还是可以将新的单元格修饰加上去,以使单元格的内容以不同的形式表现。 新生成的工作表对象是可写入的,我们除了更新原有的单元格外,还可以添加新的单元格到工作表中,这与示例2的操作是完全一样的。 最后,不要忘记调用write()方法,将更新的内容写入到文件中,然后关闭工作薄对象,这里有两个工作薄对象要关闭,一个是只读的,另外一个是可写入的。 小结 本文只是对Java Excel API中常用的方法作了介绍,要想更详尽地了解API,请大家参考API文档,或源代码。Java Excel API是一个开放源码项目,请大家关注它的最新进展,有兴趣的朋友也可以申请加入这个项目,或者是提出宝贵的意见。

创新互联主要企业基础官网建设,电商平台建设,移动手机平台,成都小程序开发等一系列专为中小企业定制网站设计产品体系;应对中小企业在互联网运营的各种问题,为中小企业在互联网的运营中保驾护航。

go限制上传文件大小

必须在对r.Body进行操作之前之前上面的操作

其他说明:

客户端(比如axios)向服务器发起超出服务器愿意接受大小的body时,服务器即便向客户端发出了类似(413:文件太大)的响应后,客户端未必会处理该响应。原因:

gopro怎么上传云端

1、需要连接一个有网络的终端,这个终端可以用单片机做个物联网板子,板子wifi连接到到gopro。

2、设置定时获取gopro的视频文件自动上传到云端。

3、GoPro现在允许无限量视频上传至其云存储服务。

Go 语言自我提升 (三次握手 - 四次挥手 - TCP状态图 - udp - 网络文件传输)

三次握手:

1. 主动发起连接请求端(客户端),发送 SYN 标志位,携带数据包、包号

2. 被动接收连接请求端(服务器),接收 SYN,回复 ACK,携带应答序列号。同时,发送SYN标志位,携带数据包、包号

3. 主动发起连接请求端(客户端),接收SYN 标志位,回复 ACK。

被动端(服务器)接收 ACK —— 标志着 三次握手建立完成( Accept()/Dial() 返回 )

四次挥手:

1. 主动请求断开连接端(客户端), 发送 FIN标志,携带数据包

2. 被动接受断开连接端(服务器), 发送 ACK标志,携带应答序列号。 —— 半关闭完成。

3. 被动接受断开连接端(服务器), 发送 FIN标志,携带数据包

4. 主动请求断开连接端(客户端), 发送 最后一个 ACK标志,携带应答序列号。—— 发送完成,客户端不会直接退出,等 2MSL时长。

等 2MSL待目的:确保服务器 收到最后一个ACK

滑动窗口:

通知对端本地存储数据的 缓冲区容量。—— write 函数在对端 缓冲区满时,有可能阻塞。

TCP状态转换:

1. 主动发起连接请求端:

CLOSED —— 发送SYN —— SYN_SENT(了解) —— 接收ACK、SYN,回发 ACK —— ESTABLISHED (数据通信)

2. 主动关闭连接请求端:

ESTABLISHED —— 发送FIN —— FIN_WAIT_1 —— 接收ACK —— FIN_WAIT_2 (半关闭、主动端)

—— 接收FIN、回复ACK —— TIME_WAIT (主动端) —— 等 2MSL 时长 —— CLOSED

3. 被动建立连接请求端:

CLOSED —— LISTEN —— 接收SYN、发送ACK、SYN —— SYN_RCVD —— 接收 ACK —— ESTABLISHED (数据通信)

4. 被动断开连接请求端:

ESTABLISHED —— 接收 FIN、发送 ACK —— CLOSE_WAIT —— 发送 FIN —— LAST_ACK —— 接收ACK —— CLOSED

windows下查看TCP状态转换:

netstat -an | findstr  端口号

Linux下查看TCP状态转换:

netstat -an | grep  端口号

TCP和UDP对比: 

TCP: 面向连接的可靠的数据包传递。 针对不稳定的 网络层,完全弥补。ACK

UDP:无连接不可靠的报文传输。 针对不稳定的 网络层,完全不弥补。还原网络真实状态。

优点                                                             缺点

TCP: 可靠、顺序、稳定                                      系统资源消耗大,程序实现繁复、速度慢

UDP:系统资源消耗小,程序实现简单、速度快                          不可靠、无序、不稳定

使用场景:

TCP:大文件、可靠数据传输。 对数据的 稳定性、准确性、一致性要求较高的场合。

UDP:应用于对数据时效性要求较高的场合。 网络直播、电话会议、视频直播、网络游戏。

UDP-CS-Server实现流程:

1.  创建 udp地址结构 ResolveUDPAddr(“协议”, “IP:port”) —— udpAddr 本质 struct{IP、port}

2.  创建用于 数据通信的 socket ListenUDP(“协议”, udpAddr ) —— udpConn (socket)

3.  从客户端读取数据,获取对端的地址 udpConn.ReadFromUDP() —— 返回:n,clientAddr, err

4.  发送数据包给 客户端 udpConn.WriteToUDP("数据", clientAddr)

UDP-CS-Client实现流程:

1.  创建用于通信的 socket。 net.Dial("udp", "服务器IP:port") —— udpConn (socket)

2.  以后流程参见 TCP客户端实现源码。

UDPserver默认就支持并发!

------------------------------------

命令行参数: 在main函数启动时,向整个程序传参。 【重点】

语法: go run xxx.go   argv1 argv2  argv3  argv4 。。。

xxx.exe:  第 0 个参数。

argv1 :第 1 个参数。

argv2 :第 2 个参数。

argv3 :第 3 个参数。

argv4 :第 4 个参数。

使用: list := os.Args  提取所有命令行参数。

获取文件属性函数:

os.stat(文件访问绝对路径) —— fileInfo 接口

fileInfo 包含 两个接口。

Name() 获取文件名。 不带访问路径

Size() 获取文件大小。

网络文件传输 —— 发送端(客户端)

1.  获取命令行参数,得到文件名(带路径)filePath list := os.Args

2.  使用 os.stat() 获取 文件名(不带路径)fileName

3.  创建 用于数据传输的 socket  net.Dial("tcp", “服务器IP+port”) —— conn

4.  发送文件名(不带路径)  给接收端, conn.write()

5.  读取 接收端回发“ok”,判断无误。封装函数 sendFile(filePath, conn) 发送文件内容

6.  实现 sendFile(filePath,  conn)

1) 只读打开文件 os.Open(filePath)

for {

2) 从文件中读数据  f.Read(buf)

3) 将读到的数据写到socket中  conn.write(buf[:n])

4)判断读取文件的 结尾。 io.EOF. 跳出循环

}

网络文件传输 —— 接收端(服务器)

1. 创建用于监听的 socket net.Listen() —— listener

2. 借助listener 创建用于 通信的 socket listener.Accpet()  —— conn

3. 读取 conn.read() 发送端的 文件名, 保存至本地。

4. 回发 “ok”应答 发送端。

5. 封装函数,接收文件内容 recvFile(文件路径)

1) f = os.Create(带有路径的文件名)

for {

2)从 socket中读取发送端发送的 文件内容 。 conn.read(buf)

3)  将读到的数据 保存至本地文件 f.Write(buf[:n])

4)  判断 读取conn 结束, 代表文件传输完成。 n == 0  break

}

绝对高分求客户端向服务器上传与下载文件的程序

==========上传部分================

一 WEB部分

1 首先把WEB页获得本地要上传的文件名

2 WEB通过脚本把本地文件名(绝对路径)给客户端组件

3 WEB脚本控制组件开始传送数据

4 最后判断是否传输成功

二 组件部分

1 建立INTERNET连接

2 连接FTP服务器

3 获得本地文件名(绝对路径)

4 返回远程即将保存的文件名

5 传送数据

6 判断是否传输成功,返回状态

WEB页获取本地文件

组件返回远程文件名

组件传送数据

返回

本例在VB6.0 +WIN2000+ IIS5.0 + SERV-U 5.0 下调试成功

VB部分

一、建立一个ActiveX DLL工程

二、更改工程名FtpConn

三、更改类名:clsPutFile

四、加入一个空模块到工程中,此模块主要对需要使用的函数进行声明,在此不多做解释,代码如下:

Option Explicit

Declare Function GetProcessHeap Lib "kernel32" () As Long

Declare Function HeapAlloc Lib "kernel32" (ByVal hHeap As Long, ByVal dwFlags As Long, ByVal dwBytes As Long) As Long

Declare Function HeapFree Lib "kernel32" (ByVal hHeap As Long, ByVal dwFlags As Long, lpMem As Any) As Long

Public Const HEAP_ZERO_MEMORY = H8

Public Const HEAP_GENERATE_EXCEPTIONS = H4

Declare Sub CopyMemory1 Lib "kernel32" Alias "RtlMoveMemory" ( _

hpvDest As Any, ByVal hpvSource As Long, ByVal cbCopy As Long)

Declare Sub CopyMemory2 Lib "kernel32" Alias "RtlMoveMemory" ( _

hpvDest As Long, hpvSource As Any, ByVal cbCopy As Long)

Public Const MAX_PATH = 260

Public Const NO_ERROR = 0

Public Const FILE_ATTRIBUTE_READONLY = H1

Public Const FILE_ATTRIBUTE_HIDDEN = H2

Public Const FILE_ATTRIBUTE_SYSTEM = H4

Public Const FILE_ATTRIBUTE_DIRECTORY = H10

Public Const FILE_ATTRIBUTE_ARCHIVE = H20

Public Const FILE_ATTRIBUTE_NORMAL = H80

Public Const FILE_ATTRIBUTE_TEMPORARY = H100

Public Const FILE_ATTRIBUTE_COMPRESSED = H800

Public Const FILE_ATTRIBUTE_OFFLINE = H1000

Type FILETIME

dwLowDateTime As Long

dwHighDateTime As Long

End Type

Type WIN32_FIND_DATA

dwFileAttributes As Long

ftCreationTime As FILETIME

ftLastAccessTime As FILETIME

ftLastWriteTime As FILETIME

nFileSizeHigh As Long

nFileSizeLow As Long

dwReserved0 As Long

dwReserved1 As Long

cFileName As String * MAX_PATH

cAlternate As String * 14

End Type

Public Const ERROR_NO_MORE_FILES = 18

Public Declare Function InternetFindNextFile Lib "wininet.dll" Alias "InternetFindNextFileA" _

(ByVal hFind As Long, lpvFindData As WIN32_FIND_DATA) As Long

Public Declare Function FtpFindFirstFile Lib "wininet.dll" Alias "FtpFindFirstFileA" _

(ByVal hFtpSession As Long, ByVal lpszSearchFile As String, _

lpFindFileData As WIN32_FIND_DATA, ByVal dwFlags As Long, ByVal dwContent As Long) As Long

Public Declare Function FtpGetFile Lib "wininet.dll" Alias "FtpGetFileA" _

(ByVal hFtpSession As Long, ByVal lpszRemoteFile As String, _

ByVal lpszNewFile As String, ByVal fFailIfExists As Boolean, ByVal dwFlagsAndAttributes As Long, _

ByVal dwFlags As Long, ByVal dwContext As Long) As Boolean

Public Declare Function FtpPutFile Lib "wininet.dll" Alias "FtpPutFileA" _

(ByVal hFtpSession As Long, ByVal lpszLocalFile As String, _

ByVal lpszRemoteFile As String, _

ByVal dwFlags As Long, ByVal dwContext As Long) As Boolean

Public Declare Function FtpSetCurrentDirectory Lib "wininet.dll" Alias "FtpSetCurrentDirectoryA" _

(ByVal hFtpSession As Long, ByVal lpszDirectory As String) As Boolean

' Initializes an application's use of the Win32 Internet functions

Public Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" _

(ByVal sAgent As String, ByVal lAccessType As Long, ByVal sProxyName As String, _

ByVal sProxyBypass As String, ByVal lFlags As Long) As Long

' User agent constant.

Public Const scUserAgent = "vb wininet"

' Use registry access settings.

Public Const INTERNET_OPEN_TYPE_PRECONFIG = 0

Public Const INTERNET_OPEN_TYPE_DIRECT = 1

Public Const INTERNET_OPEN_TYPE_PROXY = 3

Public Const INTERNET_INVALID_PORT_NUMBER = 0

Public Const FTP_TRANSFER_TYPE_ASCII = H1

Public Const FTP_TRANSFER_TYPE_BINARY = H1

Public Const INTERNET_FLAG_PASSIVE = H8000000

' Opens a HTTP session for a given site.

Public Declare Function InternetConnect Lib "wininet.dll" Alias "InternetConnectA" _

(ByVal hInternetSession As Long, ByVal sServerName As String, ByVal nServerPort As Integer, _

ByVal sUsername As String, ByVal sPassword As String, ByVal lService As Long, _

ByVal lFlags As Long, ByVal lContext As Long) As Long

Public Const ERROR_INTERNET_EXTENDED_ERROR = 12003

Public Declare Function InternetGetLastResponseInfo Lib "wininet.dll" Alias "InternetGetLastResponseInfoA" ( _

lpdwError As Long, _

ByVal lpszBuffer As String, _

lpdwBufferLength As Long) As Boolean

' Number of the TCP/IP port on the server to connect to.

Public Const INTERNET_DEFAULT_FTP_PORT = 21

Public Const INTERNET_DEFAULT_GOPHER_PORT = 70

Public Const INTERNET_DEFAULT_HTTP_PORT = 80

Public Const INTERNET_DEFAULT_HTTPS_PORT = 443

Public Const INTERNET_DEFAULT_SOCKS_PORT = 1080

Public Const INTERNET_OPTION_CONNECT_TIMEOUT = 2

Public Const INTERNET_OPTION_RECEIVE_TIMEOUT = 6

Public Const INTERNET_OPTION_SEND_TIMEOUT = 5

Public Const INTERNET_OPTION_USERNAME = 28

Public Const INTERNET_OPTION_PASSWORD = 29

Public Const INTERNET_OPTION_PROXY_USERNAME = 43

Public Const INTERNET_OPTION_PROXY_PASSWORD = 44

' Type of service to access.

Public Const INTERNET_SERVICE_FTP = 1

Public Const INTERNET_SERVICE_GOPHER = 2

Public Const INTERNET_SERVICE_HTTP = 3

' Opens an HTTP request handle.

Public Declare Function HttpOpenRequest Lib "wininet.dll" Alias "HttpOpenRequestA" _

(ByVal hHttpSession As Long, ByVal sVerb As String, ByVal sObjectName As String, ByVal sVersion As String, _

ByVal sReferer As String, ByVal something As Long, ByVal lFlags As Long, ByVal lContext As Long) As Long

' Brings the data across the wire even if it locally cached.

Public Const INTERNET_FLAG_RELOAD = H80000000

Public Const INTERNET_FLAG_KEEP_CONNECTION = H400000

Public Const INTERNET_FLAG_MULTIPART = H200000

Public Const GENERIC_READ = H80000000

Public Const GENERIC_WRITE = H40000000

' Sends the specified request to the HTTP server.

Public Declare Function HttpSendRequest Lib "wininet.dll" Alias "HttpSendRequestA" (ByVal _

hHttpRequest As Long, ByVal sHeaders As String, ByVal lHeadersLength As Long, ByVal sOptional As _

String, ByVal lOptionalLength As Long) As Integer

' Queries for information about an HTTP request.

Public Declare Function HttpQueryInfo Lib "wininet.dll" Alias "HttpQueryInfoA" _

(ByVal hHttpRequest As Long, ByVal lInfoLevel As Long, ByRef sBuffer As Any, _

ByRef lBufferLength As Long, ByRef lIndex As Long) As Integer

' The possible values for the lInfoLevel parameter include:

Public Const HTTP_QUERY_CONTENT_TYPE = 1

Public Const HTTP_QUERY_CONTENT_LENGTH = 5

Public Const HTTP_QUERY_EXPIRES = 10

Public Const HTTP_QUERY_LAST_MODIFIED = 11

Public Const HTTP_QUERY_PRAGMA = 17

Public Const HTTP_QUERY_VERSION = 18

Public Const HTTP_QUERY_STATUS_CODE = 19

Public Const HTTP_QUERY_STATUS_TEXT = 20

Public Const HTTP_QUERY_RAW_HEADERS = 21

Public Const HTTP_QUERY_RAW_HEADERS_CRLF = 22

Public Const HTTP_QUERY_FORWARDED = 30

Public Const HTTP_QUERY_SERVER = 37

Public Const HTTP_QUERY_USER_AGENT = 39

Public Const HTTP_QUERY_SET_COOKIE = 43

Public Const HTTP_QUERY_REQUEST_METHOD = 45

Public Const HTTP_STATUS_DENIED = 401

Public Const HTTP_STATUS_PROXY_AUTH_REQ = 407

' Add this flag to the about flags to get request header.

Public Const HTTP_QUERY_FLAG_REQUEST_HEADERS = H80000000

Public Const HTTP_QUERY_FLAG_NUMBER = H20000000

' Reads data from a handle opened by the HttpOpenRequest function.

Public Declare Function InternetReadFile Lib "wininet.dll" _

(ByVal hFile As Long, ByVal sBuffer As String, ByVal lNumBytesToRead As Long, _

lNumberOfBytesRead As Long) As Integer

Public Declare Function InternetWriteFile Lib "wininet.dll" _

(ByVal hFile As Long, ByVal sBuffer As String, _

ByVal lNumberOfBytesToRead As Long, _

lNumberOfBytesRead As Long) As Integer

Public Declare Function FtpOpenFile Lib "wininet.dll" Alias _

"FtpOpenFileA" (ByVal hFtpSession As Long, _

ByVal sFileName As String, ByVal lAccess As Long, _

ByVal lFlags As Long, ByVal lContext As Long) As Long

Public Declare Function FtpDeleteFile Lib "wininet.dll" _

Alias "FtpDeleteFileA" (ByVal hFtpSession As Long, _

ByVal lpszFileName As String) As Boolean

Public Declare Function InternetSetOption Lib "wininet.dll" Alias "InternetSetOptionA" _

(ByVal hInternet As Long, ByVal lOption As Long, ByRef sBuffer As Any, ByVal lBufferLength As Long) As Integer

Public Declare Function InternetSetOptionStr Lib "wininet.dll" Alias "InternetSetOptionA" _

(ByVal hInternet As Long, ByVal lOption As Long, ByVal sBuffer As String, ByVal lBufferLength As Long) As Integer

' Closes a single Internet handle or a subtree of Internet handles.

Public Declare Function InternetCloseHandle Lib "wininet.dll" _

(ByVal hInet As Long) As Integer

' Queries an Internet option on the specified handle

Public Declare Function InternetQueryOption Lib "wininet.dll" Alias "InternetQueryOptionA" _

(ByVal hInternet As Long, ByVal lOption As Long, ByRef sBuffer As Any, ByRef lBufferLength As Long) As Integer

' Returns the version number of Wininet.dll.

Public Const INTERNET_OPTION_VERSION = 40

' Contains the version number of the DLL that contains the Windows Internet

' functions (Wininet.dll). This structure is used when passing the

' INTERNET_OPTION_VERSION flag to the InternetQueryOption function.

Public Type tWinInetDLLVersion

lMajorVersion As Long

lMinorVersion As Long

End Type

' Adds one or more HTTP request headers to the HTTP request handle.

Public Declare Function HttpAddRequestHeaders Lib "wininet.dll" Alias "HttpAddRequestHeadersA" _

(ByVal hHttpRequest As Long, ByVal sHeaders As String, ByVal lHeadersLength As Long, _

ByVal lModifiers As Long) As Integer

' Flags to modify the semantics of this function. Can be a combination of these values:

' Adds the header only if it does not already exist; otherwise, an error is returned.

Public Const HTTP_ADDREQ_FLAG_ADD_IF_NEW = H10000000

' Adds the header if it does not exist. Used with REPLACE.

Public Const HTTP_ADDREQ_FLAG_ADD = H20000000

' Replaces or removes a header. If the header value is empty and the header is found,

' it is removed. If not empty, the header value is replaced

Public Const HTTP_ADDREQ_FLAG_REPLACE = H80000000

五、输入类代码,代码如下:

Option Explicit

Dim bActiveSession As Boolean

Dim hOpen As Long

Dim hConnection As Long

Dim scUserAgent As String

Dim strServer As String

Dim strUser As String

Dim strPassword As String

Dim nFlag As Long

Dim bRet As Boolean

Dim szFileLocal As String

Dim szFileRemote As String

Dim dwType As Integer

Public Function PUTFILE() As Boolean

On Error Resume Next

hOpen = InternetOpen(scUserAgent, INTERNET_OPEN_TYPE_DIRECT, vbNullString, vbNullString, 0)

hConnection = InternetConnect(hOpen, strServer, INTERNET_INVALID_PORT_NUMBER, strUser, strPassword, INTERNET_SERVICE_FTP, nFlag, 0)

bRet = FtpPutFile(hConnection, szFileLocal, szFileRemote, _

dwType, 0)

Call CloseConn

PUTFILE = bRet

End Function

Sub CloseConn()

If hConnection 0 Then InternetCloseHandle hConnection

hConnection = 0

End Sub

Function getRemoteName(filename)

Dim arrName() As String

arrName = Split(filename, ".")

Randomize

getRemoteName = Date CInt(Rnd * 1000) "." arrName(UBound(arrName))

End Function

Private Sub Class_Initialize()

scUserAgent = "My FTP"

strServer = ""

strUser = "Username"

strPassword = "Password"

nFlag = INTERNET_FLAG_PASSIVE

szFileLocal = "DefultLocalFileName"

szFileRemote = "DefultRemoteFileName"

dwType = 1

End Sub

Public Property Get connServer() As Variant

connServer = strServer

End Property

Public Property Let connServer(ByVal vNewValue As Variant)

strServer = vNewValue

End Property

Public Property Get connUser() As Variant

connUser = strUser

End Property

Public Property Let connUser(ByVal vNewValue As Variant)

strUser = vNewValue

End Property

Public Property Get connPassword() As Variant

connPassword = strPassword

End Property

Public Property Let connPassword(ByVal vNewValue As Variant)

strPassword = vNewValue

End Property

Public Property Let LocalFileName(ByVal vNewValue As Variant)

szFileLocal = vNewValue

szFileRemote = getRemoteName(vNewValue)

End Property

Public Property Get RemoteFileName() As Variant

RemoteFileName = szFileRemote

End Property

六、生成DLL

七、使用VB6的打包工具打包成“Internet ActiveX 安装包”,这是,VB打包后,还会给一个例子的HTML文件

八、建立HTML文件

HTML

HEAD

TITLEFtpConn.CAB/TITLE

/HEAD

BODY

OBJECT ID="clsPutFile"

CLASSID="CLSID:D9BACC8F-0A99-46DA-ADA3-F1C25A48AA78"

CODEBASE="FtpConn.CAB#version=1,0,0,0"

/OBJECT

INPUT type="file" name="FileName"button onclick="go()"GO~!/button

SCRIPT LANGUAGE="JavaScript"

!-- by Newrocky 2004-12-7 QQ:1936234

function go()

{

if (FileName.value!='')

{

clsPutFile.LocalFileName=FileName.value;

alert(clsPutFile.RemoteFileName);//查看远程文件名

if (clsPutFile.PutFile()) //开始传送文件,如果返回true则成功,反之失败

{

alert('上传文件成功!');

}

else

{

alert('上传文件失败!')

}

}

else

{

alert('请选择您要上传的文件');

}

}

//--

/SCRIPT

/BODY

/HTML

ok~!

===============下载部分=============

首先,声明一些变量

Dim strCommand As String

Dim strWebPage As String

为了动态设置Winsock控件的一些属性,在“开始”按钮的Click事件加入以下代码。

Winsock1.RemoteHost="192.168.100.101" '设置连接的IP地址

Winsock1.RemotePort = 80 '设置连接的远程端口号

Winsock1.Connect '开始连接远程计算机。

当Winsock控件连接操作完成,就可以传送FTP命令给服务器了,因此在Winsock控件的Connect事件中加入以下代码:

On Error Resume Next '在错误处理程序结束后,恢复原有的运行

strWebPage= " 192.168.100.101/main.htm" '设置要下载的文件'添加FTP中取得文件的命令(GET)

strCommand = "GET " + strWebPage + " HTTP/1.0" + vbCrLf

strCommand = strCommand + "Accept: */*" + vbCrLf

strCommand = strCommand + "Accept: text/html" + vbCrLf

strCommand = strCommand + vbCrLf '必须以vbCrLf结束命令

Winsock1.SendData strCommand '向远程计算机发送命令

当Winsock控件获取到数据时,需要对数据进行处理,本例中将获取的内容显示在文本框控件中,因此在Winsock控件的DataArrival事件加入以下代码:

On Error Resume Next '在错误处理程序结束后,恢复原有的运行

Dim webData As String

Winsock1.GetData webData,vbString '获取当前的数据块

Text1.Text = Text1.Text + webData '显示接收到的数据


文章题目:go语言客户端上传文件,go 引用文件
标题URL:http://cdweb.net/article/hsgpph.html