How to read text file in classic asp

2019-01-26 15:08发布

问题:

I am uploading image.While uploading images i am saving image name and the link for that iage in one textfile. like this, abc.jpeg,http://google.com

Now i want to display all that images with corresponding links using classic asp.

How should I do this?

Please help.

I used this asp code:

<%
For Each FileName in fold.Files
Dim Fname
Dim strFileName
Dim objFSO
Dim objTextFile
Dim URLString
Dim strReadLineText

Fname= mid(FileName.Path,instrrev(FileName.Path,"\\")+1)
strFileName = "../admin/Links.txt"
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

Set objTextFile = objFSO.OpenTextFile(Server.MapPath(strFileName))

URLString=""

Do While Not objTextFile.AtEndOfStream
    strReadLineText = objTextFile.ReadLine
    'response.Write(strReadLineText & "<br>")

    If strReadLineText<>"" then
        If Instr(strReadLineText,",")>0 then
            strReadLineTextArr=split(strReadLineText,",")
            response.Write(strReadLineTextArr(0))
            URLString=strReadLineTextArr(1)
        end if 
    end if
Loop

' Close and release file references

objTextFile.Close

Set objTextFile = Nothing

Set objFSO = Nothing

its displaying all images but for all images link is same.its reading directly the last link from textfile....What is the problem with my code?

回答1:

You could try something like this -

Dim lineData
Set fso = Server.CreateObject("Scripting.FileSystemObject") 
set fs = fso.OpenTextFile(Server.MapPath("imagedata.txt"), 1, true) 
Do Until fs.AtEndOfStream 
    lineData = fs.ReadLine
    'do some parsing on lineData to get image data
    'output parsed data to screen
    Response.Write lineData
Loop 

fs.close: set fs = nothing 


回答2:

Your problem is the way you assign URLString. It starts off as "", and as you read through each line in the file, you overwrite it's existing value. The last line of the file will be the last overwrite, so that'll be the value inside of URLString at the end of the loop. An example of code is:

output = ""
path = server.mappath("../admin/Links.txt")
set fs = server.createobject("Scripting.FileSystemObject")
set f = fs.OpenTextFile(path, 1, true) '1 = for reading
do while not f.AtEndOfStream
    text = trim(f.ReadLine)
    if text <> "" then
        if instr(text,",") > 0 then
            arry = split(text,",")
            ' assuming line = filename.jpg, url.com
            output = output & "<a href="""&trim(arry(1))&"""><img src="""&trim(arry(0))&""" /></a><br />"
        end if 
    end if
loop
f.close
set f = nothing
set fs = nothing

This removes extra whitespace around any text and simply writes a list of series images. The one flaw this has is that if a filename has a comma in it, it'll break.



标签: asp-classic