delphi文件上传
前言
delphi的文件上传。上传的目录、文件重复、整个文件上传这些是考虑的因素、及上传逻辑。
一、delphi文件上传
涉及一些文件、流、及基本数据数据的处理。
二、封装的方法
代码如下(示例):
//文件上传
function UploadFileToServer(const BinFolderPath, UserName, DateStr, BizID, FileName: string; const FileData: TBytes;out OriginalFileName:string): Boolean;
var
PersonFolderPath, DateFolderPath, BizFolderPath, FilePath, NewFilePath, OriginalExt, BaseNameWithoutExt: string;
DirectoryExists: Boolean;
FileStream: TFileStream;
FileCounter: Integer;
begin
// 构建完整的路径
PersonFolderPath := TPath.Combine(BinFolderPath, UserName);
DateFolderPath := TPath.Combine(PersonFolderPath, DateStr);
BizFolderPath := TPath.Combine(DateFolderPath, BizID);
// 检查并创建必要的目录
if not TDirectory.Exists(PersonFolderPath) then
TDirectory.CreateDirectory(PersonFolderPath);
if not TDirectory.Exists(DateFolderPath) then
TDirectory.CreateDirectory(DateFolderPath);
if not TDirectory.Exists(BizFolderPath) then
TDirectory.CreateDirectory(BizFolderPath);
// 使用FileName初始化OriginalFileName,因为FileName应该是原始文件名
OriginalFileName := FileName; // OriginalFileName = 'example.txt'
OriginalExt := TPath.GetExtension(OriginalFileName); // OriginalExt = '.txt'
BaseNameWithoutExt := TPath.GetFileNameWithoutExtension(OriginalFileName); // BaseNameWithoutExt = 'example'
// 构建文件完整路径
FilePath := TPath.Combine(BizFolderPath, FileName);
// 如果文件已存在,则寻找一个唯一的新文件名
FileCounter := 1;
while TFile.Exists(FilePath) do
begin
// 构建新的文件名,例如“原文件名(1).ext”、“原文件名(2).ext”...
NewFilePath := TPath.Combine(BizFolderPath, BaseNameWithoutExt + '(' + IntToStr(FileCounter) + ')' + OriginalExt);
Inc(FileCounter);
FilePath := NewFilePath;
OriginalFileName:= BaseNameWithoutExt + '(' + IntToStr(FileCounter) + ')' + OriginalExt;
end;
try
FileStream := TFileStream.Create(FilePath, fmCreate);
try
FileStream.Write(FileData, Length(FileData));
finally
FileStream.Free;
end;
Result := True;
except
on E: Exception do
begin
//Writeln('Error uploading file: ', E.ClassName, ': ', E.Message);
Result := False;
end;
end;
end;
//调用
procedure TSupQualification_Fr.HandleMultiFileUpload(const Files: TUniFileInfoArray; const BinFolderPath, UserName, DateStr, BizID: string; const ListBox: TuniListBox);
var
FileName,OriginalFileName: string;
FileData: TBytes;
UploadResult: Boolean;
begin
for var I := Low(Files) to High(Files) do
begin
// 获取文件名称
FileName := ExtractFileName(Files[I].FileName);
// 获取文件大小并读取文件内容
SetLength(FileData, Files[I].Stream.Size);
Files[I].Stream.Position := 0;
Files[I].Stream.Read(FileData[0], Length(FileData));
DeleteFile('');
// 上传文件到服务器并处理结果
UploadResult := UploadFileToServer(BinFolderPath, UserName, DateStr, BizID, FileName, FileData,OriginalFileName);
if UploadResult then
ListBox.Items.Add(OriginalFileName);
end;
// 显示成功消息
if ListBox.Items.Count = Length(Files) then
ShowOKMsg('上传成功');
end;
总结
提示:1.FileName := ExtractFileName(flbtnautre.FileName[I]); 会报错 range error 2.通过流获取,没有展示真实的文件上传名称
就实现了一个简单的文件上传。