mormot上传文件


//服务器代码

(AContext: THttpServerRequest)

if Pos('multipart/form-data', AContext.InContentType) > 0 then
begin
  upload(AContext.InContentType, AContext.InContent); 
end;

//从请求中获取文件,保存到本地

function Upload(mimetype, params: RawUTF8): Boolean;
var
parts: TMultiPartDynArray;
i: Integer;
filename: string;
ss: TStringStream;
begin
Result := False;
try
MultiPartFormDataDecode(mimetype, params, parts);
if Length(parts) =0 then
begin
OutValue := '无文件!请检查!';
Exit;
end;
for i := 0 to high(parts) do
begin
if sametext(parts[i].Name, 'file') then
begin
ss := TStringStream.Create(parts[i].Content);
try
ss.SaveToFile(FPATH + '\' + parts[i].filename)
finally
ss.Free;
end;
end
else
begin
OutValue := '上传文件格式错误!请指定文件参数key=file!';
Exit
end;
end;
except
on e: Exception do
begin
OutValue := '文件保存出错!' + e.Message;
Exit
end;
end;
OutValue := '成功';
Result := True;
end;

客户端上传使用multipart/form-data格式,贴一个postman的上传示例,key一定要指定file:

相关