File is still in use after Multipart post - delphi

Environment: Delphi 2010, Indy10
I know I am not alone with the problem...
File is Still in Use Error 32 How can I free it?
But after some days of fight I give up.
My code
var
multi: TIdMultipartFormDataStream;
ss: TStringStream;
FHTTP: TIdHTTP;
FHTTP := TidHTTP.Create(nil);
Multi:=TidMultiPartFormDataStream.Create;
Multi.AddFormField('eventid', TSettingsManager.GetAppSettings('EventID'));
Multi.AddFormField('password', TSettingsManager.GetAppSettings('EventPassword'));
Multi.AddFile('file', filename, 'image/jpeg'); //GetMIMETypeFromFile(fileName));
try
FHTTP.Post(TSettingsManager.GetAppSettings('WEBServer') + '/upload', Multi, ss);
finally
Multi.Clear;
FreeAndNil(Multi);
FreeAndNil(FHTTP);
end;
IOUtils.TFile.Delete(filename);
I have exception "The file is in use" when I try to delete the file.
How should I act to get file free and then delete it?

There is no error in the code shown.
Some potential memory leaks can be seen, which can be fixed easily with proper usage of try .. finally.
Also iirc you can create an instance of TIdHTTP with no owner in a shorter way. Instead of:
HTTP := TIdHTTP.Create(nil);
you can just leave away the argument:
HTTP := TIdHTTP.Create;

Related

Handling BabyFTP MKD 250 response with Indy

I'm using BabyFTP as an embedded FTP server for a Delphi 10.1 Berlin application. Even though I'm still not sure it's the best lightweight FTP server I can use with my requirements, it seems to be working well enough... except for one detail:
On a successful MKD command, BabyFTP responds with a 250, instead of the expected (by RFC and Indy) 257. Because of this the TIdFTP raises an EIdReplyRFCError exception which breaks the flow of what I'm trying to do (save a blob field to a file):
s := TBytesStream.Create;
Try
Field.SaveToStream(s);
MakeDir(TPath.GetDirectoryName(url));
Put(s, url);
Finally
s.Free;
End;
Of course, I know I could wrap the MakeDir line in a Try Except block and ignore the specific exception type. But this seems a bit risky as from the raised exception I can't be sure I got a 250 or some other real error.
I've tried looking if Indy's response codes are somehow configurable, but it seems they are hard coded in the specific methods. Subclassing TIdFTP is not feasible as the methods are not virtual. I could customize the IdFTP.pas unit, but I don't want to do that as I'm working in a team and I prefer not having to distribute patches to standard Delphi units.
I could use another FTP server... but I suppose most of them have some not perfectly standard feature like this one.
Does anyone know of other workarounds? Remy?
Ondrej's answer explains how to address the issue of handling a 250 reply in TIdFTP.MakeDir().
Note that TIdFTP.MakeDir() is just a wrapper for TIdTCPConnection.SendCmd():
procedure TIdFTP.MakeDir(const ADirName: string);
begin
SendCmd('MKD ' + ADirName, 257); {do not localize}
end;
SendCmd() is public, so an alternative solution would be to call SendCmd() directly and tell it that 250 is an acceptable reply code:
s := TBytesStream.Create;
Try
Field.SaveToStream(s);
//MakeDir(TPath.GetDirectoryName(url));
SendCmd('MKD ' + TPath.GetDirectoryName(url), [250, 257]);
Put(s, url);
Finally
s.Free;
End;
Or, to accept any 2xx reply code, you can do this:
s := TBytesStream.Create;
Try
Field.SaveToStream(s);
//MakeDir(TPath.GetDirectoryName(url));
if (SendCmd('MKD ' + TPath.GetDirectoryName(url)) div 100) <> 2 then
RaiseExceptionForLastCmdResult;
Put(s, url);
Finally
s.Free;
End;
You could handle just the specific case of EIdReplyRFCError when its ErrorCode property equals 250, re-raising in any other case.
s := TBytesStream.Create;
Try
Field.SaveToStream(s);
Try
MakeDir(TPath.GetDirectoryName(url));
Except
on E: EIdReplyRFCError do
if E.ErrorCode <> 250 then raise;
end
Put(s, url);
Finally
s.Free;
End;

how do i save image and use them later in Idhttp

by Follow up to my previous question about update listview inside thread here
i start to think in different way to get my previous question solved , because of download process takes too long and takes much bandwidth i want to download GIFimage then save it on disk then use it later inside my application
this is current download thread code
procedure TDownloadImage.Execute;
var
aMs: TMemoryStream;
aIdHttp: TIdHttp;
begin
FGif := TGifImage.Create;
try
aMs := TMemoryStream.Create;
try
aIdHttp := TIdHttp.Create(nil);
try
aIdHttp.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0';
aIdHttp.Get(FURL, aMs); // here is the client FURL
finally
aIdHttp.Free;
end;
aMs.Position := 0;
FGif.LoadFromStream(aMs);
FGif.Transparent := True;
finally
aMs.Free;
end;
if Assigned(FOnImageReady) then
Synchronize(DoImageReady);
end;
finally
FGif.Free;
end;
end;
i want to save image of FURL on computer client then if this image requested to be download again abort download process and load it from client computer how possibly i can do that ?
As TLama Said wisely, you are looking for a Full Cache mechanism. In Delphi you may want to call it TDictionary.
If you want to save your Gif and URI in memory, then you can use a TDictionary pair, to hold each memory stream and uri, and everything will work fast.
If you want to store the data on files, and each time the application starts to remember the state of previous run, you may want to find a way to store the data, a database, or text file.
If you want a simple text file that can help, an Ini file can do the job, however, as text file grow, then tend to get slow, and make the search slower, then the file fetch.
If you work with a good portable database , maybe the search will be fast.
example code with Ini file to get you started:
pseudo code.
var
filename:string;//where is the key value is stored.
GifLocation:string;//result of the cache hit.
const
URI = 'http://sstatic.net/stackexchange/img/logos/so/so-logo-med.png?v=a4a65015804e';
begin
with TIniFile.create(filename) do
try
GifLocation := readString('FilesLocation',URI,'');
finally
free;
end;
if ('' = GifLocation) then
fetchBoy(URI)
else IGotIt_IGotIt(GifLocation);
end;
Implement your fetchBoy, for doing an http get, and IGotIt_IGotIt to load file stream.

Delphi: How to load a text file on the internet into a string?

On my program I have a function that checks for the current version of the program, which it gets from the url: www.tablemaster.webs.com/versioninfo.txt
As you can see, at the URL is just plain text. I need to load this text from the URL into a string on my program, how will I go about doing this? I've searched around but found nothing..
PS: I need the simplest code possible..
Thanks in advance :)
I would use Indy's TIdHTTP with it's easiest GET overload this way:
uses
IdHTTP;
procedure TForm1.Button1Click(Sender: TObject);
var
S: string;
IdHTTP: TIdHTTP;
begin
IdHTTP := TIdHTTP.Create(nil);
try
S := IdHTTP.Get('http://www.tablemaster.webs.com/versioninfo.txt');
ShowMessage(S);
finally
IdHTTP.Free;
end;
end;
you can use TIEHTTP component from myfxboard..
to load txt file from url with TIEHTTP:
http.ExecuteURL('www.tablemaster.webs.com/versioninfo.txt');
Memo1.Lines.Add(http.sl.Text);
I would use MSXML2_TLB, especially if I already use XML in the project. MSXML2 is present in Windows since version Internet Explorer 5.5, so chances are real good it's present on the system. You can get MSXML2_TLB.pas using the Import Type Library option from the main menu, and selecting "Microsoft XML, v6.0" (or higher) from the list.
var
r:XMLHTTP;
begin
r:=CoXMLHTTP.Create;
r.open('GET','http://www.tablemaster.webs.com/versioninfo.txt','','');
r.send(EmptyParam);
if r.status<>200 then raise Exception.Create(IntToStr(r.status)+' '+r.statusText);
Result:=r.responseText;
end;
uses
IdHTTP;
procedure TForm1.Button1Click(Sender: TObject);
var
.
.
it seems in this method system cached the txt file so if the file change on web this method denies changes.!

Download, pause and resume an download using Indy components

Actually i'm using the TIdHTTP component for download a file from internet. i'm wondering if is possible pause and resume the download using this component o maybe another indy component.
this is my current code, this works ok for download a file (without resume), but . now i want pause the download close my app ,and when my app restart then resume the download from the last position saved.
var
Http: TIdHTTP;
MS : TMemoryStream;
begin
Result:= True;
Http := TIdHTTP.Create(nil);
MS := TMemoryStream.Create;
try
try
Http.OnWork:= HttpWork;//this event give me the actual progress of the download process
Http.Head(Url);
FSize := Http.Response.ContentLength;
AddLog('Downloading File '+GetURLFilename(Url)+' - '+FormatFloat('#,',FSize)+' Bytes');
Http.Get(Url, MS);
MS.SaveToFile(LocalFile);
except
on E : Exception do
Begin
Result:=False;
AddLog(E.Message);
end;
end;
finally
Http.Free;
MS.Free;
end;
end;
the following code worked to me. It downloads the file by chunks:
procedure Download(Url,LocalFile:String;
WorkBegin:TWorkBeginEvent;Work:TWorkEvent;WorkEnd:TWorkEndEvent);
var
Http: TIdHTTP;
quit:Boolean;
FLength,aRangeEnd:Integer;
begin
Http := TIdHTTP.Create(nil);
fFileStream:=nil;
try
try
Http.OnWork:= Work;
Http.OnWorkEnd := WorkEnd;
Http.Head(Url);
FLength := Http.Response.ContentLength;
quit:=false;
repeat
if not FileExists(LocalFile) then begin
fFileStream := TFileStream.Create(LocalFile, fmCreate);
end
else begin
fFileStream := TFileStream.Create(LocalFile, fmOpenReadWrite);
quit:= fFileStream.Size >= FLength;
if not quit then
fFileStream.Seek(Max(0, fFileStream.Size-4096), soFromBeginning);
end;
try
aRangeEnd:=fFileStream.Size + 50000;
if aRangeEnd < fLength then begin
Http.Request.Range := IntToStr(fFileStream.Position) + '-'+ IntToStr(aRangeEnd);
end
else begin
Http.Request.Range := IntToStr(fFileStream.Position) + '-';
quit:=true;
end;
Http.Get(Url, fFileStream);
finally
fFileStream.Free;
end;
until quit;
Http.Disconnect;
except
on E : Exception do
Begin
//Result:=False;
//AddLog(E.Message);
end;
end;
finally
Http.Free;
end;
end;
Maybe the HTTP RANGE header can help you here. Have a look at archive.org's copy of http://www.west-wind.com/Weblog/posts/244.aspx for more info on resuming HTTP downloads:
(2004-02-07) A couple of days ago somebody on the Message Board asked an interesting question about how to provide resumable HTTP downloads. My first response to this question was that this isn't possible since HTTP is a stateless protocol that has no concept of file pointers and thus can't resume an HTTP download.
However it turns out HTTP 1.1 does have the ability to specify ranges in downloads by using the Range: header in the Http header sent form the client. You can do things like:
Range: 0-10000
Range: 100000-
Range: -100000
which download the first 100000 bytes, everything over 100000 bytes or the last 100000 bytes. There are more combinations but the first two are the ones that are of interest for a resumable download.
To demonstrate this feature I used wwHTTP (in Web Connection/VFP) to download a first 400k chunk of a file into a file with HTTPGetEx which is meant to simulate an aborted download. Next I do a second request to pick up the existing file and download the remainder:
#INCLUDE wconnect.h
CLEAR
CLOSE DATA
DO WCONNECT
LOCAL o as wwHTTP
lcDownloadedFile = "d:\temp\wwipstuff.zip"
*** Simulate partial output
lcOutput = ""
Text=""
tnSize = 0
o = CREATEOBJECT("wwHTTP")
o.HttpConnect("www.west-wind.com")
? o.httpgetex("/files/wwipstuff.zip",#Text,#tnSize,"Range: bytes=0-400000"+CRLF,lcDownloadedFile)
o.Httpclose()
lcOutput = Text
? LEN(lcOutput)
*** Figure out how much we downloaded
lnOpenAt = FILESIZE(lcDownloadedFile)
*** Do a partial download starting at this byte count
Text=""
tnSize =0
o = CREATEOBJECT("wwHTTP")
o.HttpConnect("www.west-wind.com")
? o.httpgetex("/files/wwipstuff.zip",#Text,#tnSize,"Range: bytes=" + TRANSFORM(lnOpenAt) + "-" + CRLF)
o.Httpclose()
? LEN(Text)
*** Read the existing partial download and append current download
lcOutput = FILETOSTR(lcDownloadedFile) + TEXT
? LEN(lcOutput)
STRTOFILE(lcOutput,lcDownloadedFile)
RETURN
Note that this approach uses a file on disk, so you have to use HTTPGetEx (with Web Connection). The second download can also be done to disk if you choose, but things will get tricky if you have multiple aborts and you need to piece them together. In that case you might want to try to keep track of each file and add a number to it, then combine the result at the very end.
If you download to memory using WinInet (which is what wwHTTP uses behind the scenes) you can also try to peel out the file from the Temporary Internet Files cache. Although this works I suspect this process will become very convoluted quickly so if you plan on providing the ability to resume I would highly recommend that you write your output to file yourself using the approach above.
Some additional information on WinInet and some of the requirements for this approach to work with it are described here: http://www.clevercomponents.com/articles/article015/resuming.asp.
The same can be done with wwHTTP for .Net by adding the Range header to the wwHTTP:WebRequest.Headers object.
(Randy Pearson) Say you don't know what the file size is at the server. Is there a way to find this out, so you can know how many chunks to request, for example? Would you send a HEAD request first, or does the header of the GET response tell you the total size also?
(Rick Strahl) You have to read the Content-Length: header to get the size of the file downloaded. If you're resuming this shouldn't matter - you just use Range: (existingsize)- to get the rest. For chunky downloads you can read the content length and only download the first x bytes. This gets tricky with wwHTTP - you have to make individual calls with HTTPGetEx and set the tnBufferSize parameter to the chunk size to retrieve to have it stop after the size is reached.
(Randy Pearson) Follow-up: It looks like a compliant server would send you enough to know the size. If it provides chunks it should reply with something like:
Content-Range: 0-10000/85432
so you could (if desired) extract that and use it in a loop to continue with intelligent chunk requests.
Also look here https://forums.embarcadero.com/message.jspa?messageID=219481 for TIdHTTP related discussion on the same topic:
(at least partly as per tfilestream.seek and offset confusion)
if FileExists(dstFile) then
begin
Fs := TFileStream.Create(dstFile, fmOpenReadWrite);
try
Fs.Seek(Max(0, Fs.Size-1024), soFromBeginning);
// alternatively:
// Fs.Seek(-1024, soFromEnd);
Http.Request.Range := IntToStr(Fs.Position) + '-';
Http.Get(Url, Fs);
finally
Fs.Free;
end;
end;

Can I send request in PUT and DELETE in Delphi 7?

I need to send PUT and DELETE along with POST, GET to a REST API how can I do it?
Delphi 7 comes with Indy. See the TIdHTTP component and specificly the Get and Put methods.
Or look at the open source Synapse library. There are some simple function calls in the HTTPSend unit which make implementing this completely painless. Just use the sample functions/procedures as your model for the PUT/DELETE. The existing routines already supply the POST and GET. The difference is in the method passed.
Personally I have found this library to be perfectly matched for working with REST. Its simple, well written and easy to extend.
For example, here is a simple put that sends and receives a stream:
function HttpPutBinary(const URL: string; const Data: TStream): Boolean;
var
HTTP: THTTPSend;
begin
HTTP := THTTPSend.Create;
try
HTTP.Document.CopyFrom(Data, 0);
HTTP.MimeType := 'Application/octet-stream';
Result := HTTP.HTTPMethod('PUT', URL); // changed method from 'POST'
Data.Size := 0;
if Result then
begin
Data.Seek(0, soFromBeginning);
Data.CopyFrom(HTTP.Document, 0);
end;
finally
HTTP.Free;
end;
end;
Check out the ICS components, they are suitable for the job.

Resources