我很有意思发送一个文件及其文件名。
服务器选项:
-define(TCP_OPTIONS_SERVER, [binary, {packet, 0}, {active, false}]).
这是接收器循环:
file_receiver_loop(Socket,Bs)->
case gen_tcp:recv(Socket, 0) of
{ok, B} ->
file_receiver_loop(Socket, [Bs, B]);
{error, closed} ->
io:format("~nReceived!~n ~p",[Bs]),
save_file(Bs)
end.
我发送文件:
file:sendfile(FilePath, Socket),
当我发送文件和文件名时
gen_tcp:send(Socket,Filename),
file:sendfile(FilePath, Socket),
二进制数据具有可变结构。
全部谢谢!
答案 0 :(得分:0)
我制作此代码来解决问题 我发送30个字节的文件名 如果文件名<30,我使用带白色字符的填充 当接受连接时,我调用函数file_name_receiver(Socket),它接收文件名:
file_name_receiver(Socket)->
{ok,FilenameBinaryPadding}=gen_tcp:recv(Socket,30),
FilenamePadding=erlang:binary_to_list(FilenameBinaryPadding),
Filename = string:strip(FilenamePadding,both,$ ),
file_receiver_loop(Socket,Filename,[]).
这个函数可以对二进制数据文件进行处理:
file_receiver_loop(Socket,Filename,Bs)->
io:format("~nRicezione file in corso~n"),
case gen_tcp:recv(Socket, 0) of
{ok, B} ->
file_receiver_loop(Socket, Filename,[Bs, B]);
{error, closed} ->
save_file(Filename,Bs)
end.
最后,此功能保存文件。
%%salva il file
save_file(Filename,Bs) ->
io:format("~nFilename: ~p",[Filename]),
{ok, Fd} = file:open("../script/"++Filename, write),
file:write(Fd, Bs),
file:close(Fd).
发件人使用简单的功能:
%%Permette l'invio di un file specificando host,filename e path assoluto
send_file(Host,Filename,FilePath,Port)->
{ok, Socket} = gen_tcp:connect(list_to_atom(Hostname), Port, TCP_OPTIONS_CLIENT),
FilenamePadding = string:left(Filename, 30, $ ), %%Padding with white space
gen_tcp:send(Socket,FilenamePadding),
Ret=file:sendfile(FilePath, Socket),
ok = gen_tcp:close(Socket).
答案 1 :(得分:0)
我做了两个功能,可以通过消息传递来发送二进制文件。
%Zip a file or a folder
send_zip(Pid, FolderName) ->
%Name of you zip file
FolderNameZip= FolderName++".zip",
%Zip the folder/file from the computer and name the zip file by FornderNameZip
{ok, ZipFile} = zip:create(FolderNameZip, [FolderName]),
%Put the Zipfile in a variable
{ok, ZipHandle} = file:read_file(ZipFile),
%Send the zipfile to the other PID, sends the zipfile and his name to name it the same way.
Pid ! {finish, ZipHandle, FolderNameZip}.
%save and unzip the in the computer
register_zip_bash(Dir, ZipHandle, FolderNameZip) ->
file:write_file(FolderNameZip, ZipHandle),
Cmd2 = io_lib:format("unzip -o -j ~p -d ~p/",[FolderNameZip, Dir]),
_=os:cmd(Cmd2).
FoldeName可以是计算机中文件或文件夹的名称。 Pid是您要发送消息的人。
当您收到ZipHandle和FolderNameZip时,使用register_zip_bash(...)函数将数据保存在计算机中。 目录是您要保存数据的目录。 ZipHandle是从PID函数接收的二进制文件。 FolderNameZip是将ZipHandle保存在计算机中的名称。
如您所见,send_zip(...)使用erlang函数,register_zip_bash(...)使用bash命令。您无需压缩文件即可发送数据。不要犹豫,更改代码以使其适合您。
希望这会有所帮助, 干杯。