SD Card list files to HTML strange output

Hi,
I’m creating a web output from a Mega 2560 for senzors value and sd card content and I use the code belllow that I found on a site. The strange problem is that the output of the file names is not a string, but a number like for instance as in the bellow output. Whay doesn’t print correctly the filenames?

SD Card Files:
73667795767912649.698869
86796865707912649.698869
667979846988.767971
83698286736773/
6873837549/

Arduino sketch is this:

/*
 Web Server
 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield. 
created 18 Dec 2009
 by David A. Mellis
 modified 4 Sep 2010
 by Tom Igoe
*/
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,100, 199);
// Initialize the Ethernet server library with the IP address and port you want to use (port 80 is default for HTTP):
EthernetServer server(80);

 // include the SD library:
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module, Arduino Ethernet shield: pin 4
const int chipSelect = 4;  

void setup()
{
  Serial.begin(9600);
  Ethernet.begin(mac, ip);  // start the Ethernet connection and the server:
  server.begin();
}

#define BUFSIZ 100
void loop()
{
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        // if you've gotten to the end of the line (received a newline character) and the line is blank, the http request has ended, so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          // output the value of each analog input pin
          client.print("<html><head><title>test page</title><meta http-equiv='refresh' content='5'></head><body><b>page title</b><hr />
<table border=1><tr><td><b>SENZOR</b></td><td><b>TYPE</b></td><td><b>PIN</b></td><td><b>VALUE</b></td></tr>");
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            if (analogChannel == 0) {
                client.print("<tr><td>LIGHT</td><td>A</td><td>"); //example of senzor
                client.print(analogChannel);
                client.print("</td><td>");
                client.print(analogRead(analogChannel));
                client.print("</td></tr>");
            }
            else{
                client.print("<tr><td>N/A</td><td>A</td><td>");
                client.print(analogChannel);
                client.print("</td><td>");
                client.print(analogRead(analogChannel));
                client.print("</td></tr>");
            }
          }
          for (int digitalChannel = 0; digitalChannel < 54; digitalChannel++) {
                client.print("<tr><td>N/A</td><td>D</td><td>");
                client.print(digitalChannel);
                client.print("</td><td>");
                client.print(digitalRead(digitalChannel));
                client.print("</td></tr>");
          }
          client.print("</table></body><hr />");
          
          //Start SD Card files explorer section
          client.println("<h2>SD Card Files:</h2>");
          // print all the files on the SD Card
          pinMode(53, OUTPUT);     // change this to 53 on a mega
          // we'll use the initialization code from the utility libraries since we're just testing if the card is working!
          if (!card.init(SPI_HALF_SPEED, chipSelect)) {
            Serial.println("initialization failed. Things to check:* card is inserted? * wiring correct?did you change the chipSelect pin to match shield/module?");
            return;
          } else {
           Serial.println("SD Card is present."); 
          }
          if (!volume.init(card)) {
            Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
            return;
          }
          
          root.openRoot(volume);  //access the root of the SD card volume
          // list all files in the card with date and size
          root.ls(LS_R | LS_DATE | LS_SIZE);  //for serial box output
          dir_t p;
          root.rewind();
          client.println("<ul>");
          while (root.readDir(p) > 0) {
            // done if past last used entry
            if (p.name[0] == DIR_NAME_FREE) break;
         
            // skip deleted entry and entries for . and  ..
            if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue;
         
            // only list subdirectories and files
            if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;
         
            // print any indent spaces
            client.print("<li><a href=\"");
            for (uint8_t i = 0; i < 11; i++) {
              if (p.name[i] == ' ') continue;
              if (i == 8) {
                client.print('.');
              }
              client.print(p.name[i]);
            }
            client.print("\">");
         
            // print file name with possible blank fill
            for (uint8_t i = 0; i < 11; i++) {
              if (p.name[i] == ' ') continue;
              if (i == 8) {
                client.print('.');
              }
              client.print(p.name[i]);
            }
            client.print("</a>");
         
            if (DIR_IS_SUBDIR(&p)) {
              client.print('/');
            }
 
            // print modify date/time if requested
            if (0 & LS_DATE) {
               root.printFatDate(p.lastWriteDate);
               client.print(' ');
               root.printFatTime(p.lastWriteTime);
            }
            // print size if requested
            if (!DIR_IS_SUBDIR(&p) && (0 & LS_SIZE)) {
              client.print(' ');
              client.print(p.fileSize);
            }
            client.println("</li>");
          }
          client.println("</ul>");
          
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } 
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
  }
}

you need to write
file.write(String(filename))
you need to convert that to String befor print

I changed the part where the filenames are written to html as seen bellow:

// print any indent spaces
            client.print("<li><a href=\"");
            for (uint8_t i = 0; i < 11; i++) {
              if (p.name[i] == ' ') continue;
              if (i == 8) {
                client.print('.');
              }
              client.print(String(p.name[i]));
            }
            client.print("\">");
         
            // print file name with possible blank fill
            for (uint8_t i = 0; i < 11; i++) {
              if (p.name[i] == ' ') continue;
              if (i == 8) {
                client.print('.');
              }
              client.print(String(p.name[i]));
            }

But the output is the same (for now I commented the datetime and size part of the code, for simplicity):

SD Card Files:
76738384656712649.848884
65826885737879.728477
7865787984656683.7483

oops now i get what you need
so you need to write client.write() function instead of client.print()

and dont use that String in client.write

That was great. Now I've uncommented the date and file size section and used the client.write method and they don't show nothing.

// print modify date/time if requested
            if (0 & LS_DATE) {
               client.write(p.lastWriteDate);
               client.print(' ');
               //root.printFatTime(p.lastWriteTime);
            }
            // print size if requested
            if (!DIR_IS_SUBDIR(&p) && (0 & LS_SIZE)) {
              client.print(' ');
              client.write(p.fileSize);
            }

New HTML output for files is:

SD Card Files:
LISTAC~1.TXT
ARDUINO.HTM

You have a number of problems with print date and size.

  if (0 & LS_DATE)

and

  if (!DIR_IS_SUBDIR(&p) && (0 & LS_SIZE))

will always be false so the date and size will not be printed.

The code was derived from SdFat's ls() which had an options flag in place of the zero like this:

if (flags & LS_DATE)

and

if (!DIR_IS_SUBDIR(&dir) && (flags & LS_SIZE))
client.write(p.lastWriteDate);

will not print a date. lastWriteDate is the date in a 16-bit packed DOS format. SdFat prints the date with this function:

void SdBaseFile::printFatDate(Print* pr, uint16_t fatDate) {
  pr->print(FAT_YEAR(fatDate));
  pr->write('-');
  print2u(pr, FAT_MONTH(fatDate));
  pr->write('-');
  print2u(pr, FAT_DAY(fatDate));
}
client.write(p.fileSize);

will not print the fileSize. fileSize is a 32-bit unsigned so here you need print like this:

client.print(p.fileSize);

I'm having the same exact problem. fat16lib, you mentioned what was wrong with the code but I'm confused as to what to change it to to work with the SD.h library. Has anyone found any working examples of displaying SD card info using the ethernet card and the SD.h library. I would use SDfat library but I'd have to change a bunch of other code and I'm lost as to how to open files with that library.

Hi Boys !

Check that code for sdcard list with date,size html printing. Working fine here ! 8)

add void ListFiles() call it in the void loop() with : ListFiles(client, LS_SIZE | LS_DATE);

here the code :

/*
Web Server
A simple web server that shows the value of the analog input pins.
using an Arduino Wiznet Ethernet shield.
created 18 Dec 2009
by David A. Mellis
modified 4 Sep 2010
by Tom Igoe
*/
#include <SPI.h>
#include <Ethernet.h>
byte mac = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,0, 101);
// Initialize the Ethernet server library with the IP address and port you want to use (port 80 is default for HTTP):
EthernetServer server(80);

// include the SD library:
#include <SD.h>
#include <SdFat.h>

char str[3];

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// store error strings in flash to save RAM
#define error(s) error_P(PSTR(s))

void error_P(const char* str) {
PgmPrint("error: ");
SerialPrintln_P(str);
if (card.errorCode()) {
PgmPrint("SD error: ");
Serial.print(card.errorCode(), HEX);
Serial.print(’,’);
Serial.println(card.errorData(), HEX);
}
while(1);
}

// change this to match your SD shield or module, Arduino Ethernet shield: pin 4
const int chipSelect = 4;

void setup()
{
pinMode(10, OUTPUT); // set the SS pin as an output (necessary!)
digitalWrite(10, HIGH); // but turn off the W5100 chip!
Serial.begin(9600);

if (!card.init(SPI_HALF_SPEED, 4)) error(“card.init failed!”);

// initialize a FAT volume
if (!volume.init(&card)) error(“vol.init failed!”);

PgmPrint(“Volume is FAT”);
Serial.println(volume.fatType(),DEC);
Serial.println();

if (!root.openRoot(&volume)) error(“openRoot failed”);

// list file in root with date and size
PgmPrintln(“Files found in root:”);
root.ls(LS_DATE | LS_SIZE);
Serial.println();

// Recursive list of all directories
PgmPrintln(“Files found in all dirs:”);
root.ls(LS_R);

Serial.println();
PgmPrintln(“Done”);

Ethernet.begin(mac, ip); // start the Ethernet connection and the server:
// Ethernet.begin(mac); // DHCP start the Ethernet connection and the server:
server.begin();
}

#define BUFSIZ 100
void loop()
{
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you’ve gotten to the end of the line (received a newline character) and the line is blank, the http request has ended, so you can send a reply
if (c == ‘\n’ && currentLineIsBlank) {
// send a standard http response header
client.println(“HTTP/1.1 200 OK”);
client.println(“Content-Type: text/html”);
client.println();

// output the value of each analog input pin
// client.print("test pagepage title


"); client.print("test pagepage title
SENZOR TYPE PIN VALUE
"); for (int analogChannel = 0; analogChannel < 6; analogChannel++) { if (analogChannel == 0) { client.print(""); } else{ client.print(""); } } for (int digitalChannel = 0; digitalChannel < 10; digitalChannel++) { client.print(""); } client.print("
SENZOR TYPE PIN VALUE
LIGHT A "); //example of senzor client.print(analogChannel); client.print(" "); client.print(analogRead(analogChannel)); client.print("
N/A A "); client.print(analogChannel); client.print(" "); client.print(analogRead(analogChannel)); client.print("
N/A D "); client.print(digitalChannel); client.print(" "); client.print(digitalRead(digitalChannel)); client.print("

");

/// SD CARD LIST TO ETH

//Start SD Card files explorer section
client.println(“

SD Card Files:

”);
// print all the files on the SD Card
//pinMode(10, OUTPUT); // change this to 53 on a mega
// we’ll use the initialization code from the utility libraries since we’re just testing if the card is working!
if (!card.init(SPI_HALF_SPEED, chipSelect)) {
Serial.println(“initialization failed. Things to check:* card is inserted? * wiring correct?did you change the chipSelect pin to match shield/module?”);
client.print(“

initialization failed. Check card !

”);
return;
} else {
Serial.println(“SD Card is present.”);
//client.println(“SD Card is present.”);
}
if (!volume.init(card)) {
Serial.println(“Could not find FAT16/FAT32 partition.\nMake sure you’ve formatted the card”);
client.print(“

Could not find FAT16/FAT32 partition. Make sure you’ve formatted the card

”);
return;
}
Serial.println(“List It !”);
//client.println(“List It !”);
ListFiles(client, LS_SIZE | LS_DATE);
break;

}
if (c == ‘\n’) {
// you’re starting a new line
currentLineIsBlank = true;
}
else if (c != ‘\r’) {
// you’ve gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}

void ListFiles(EthernetClient client, uint8_t flags) {
// This code is just copied from SdFile.cpp in the SDFat library
// and tweaked to print to the client output in html!
dir_t p;

root.rewind();
client.println("

    ");
    while (root.readDir(p) > 0) {
    // done if past last used entry
    if (p.name[0] == DIR_NAME_FREE) break;

    // skip deleted entry and entries for . and …
    if (p.name[0] == DIR_NAME_DELETED || p.name[0] == ‘.’) continue;

    // only list subdirectories and files
    if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;

    // print any indent spaces
    client.print("

  • <a href="");
    for (uint8_t i = 0; i < 11; i++) {
    if (p.name == ’ ') continue;

    • if (i == 8) {*
    • client.print(’.’);*
    • }*
      _ client.write(p.name*);_
      _
      }_
      _
      client.print("">");*_

    * // print file name with possible blank fill*
    * for (uint8_t i = 0; i < 11; i++) {
    _ if (p.name == ’ ') continue;
    if (i == 8) {
    client.print(’.’);
    }
    client.write(p.name);
    }*_

    * client.print("");*

    * if (DIR_IS_SUBDIR(&p)) {
    _ client.print(’/’);
    }*_

    * // print modify date/time if requested*
    * if (flags & LS_DATE) {
    // uint16_t fatDate;
    // uint16_t fatTime;
    _ client.print(’ ‘);_
    client.print(FAT_YEAR(p.lastWriteDate));
    _ client.print(’-’);_
    printTwoDigits(FAT_MONTH(p.lastWriteDate));
    _ client.print(str);
    client.print(’-’);_

    printTwoDigits(FAT_DAY(p.lastWriteDate));
    _ client.print(str);
    client.print(’ ‘);_

    printTwoDigits(FAT_HOUR(p.lastWriteTime));
    _ client.print(str);
    client.print(’:’);_

    printTwoDigits(FAT_MINUTE(p.lastWriteTime));
    _ client.print(str);
    client.print(’:’);_

    printTwoDigits(FAT_SECOND(p.lastWriteTime));
    _ client.print(str);*_

    * }*
    * // print size if requested*
    * float Size =p.fileSize;*
    * if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) {
    _ client.print(’ ');
    client.print("SIZE : ");*_

    * if (p.fileSize > 1048576){*
    * Size = Size/1048576;*
    * client.print(Size,2);*
    * client.print(“Mo”);*
    * }*

    * else if (p.fileSize > 1024){*
    * Size = Size/1024;*
    * client.print(Size,2);*
    * client.print(“Ko”);*
    * }*
    * else{*
    * client.print(p.fileSize);*
    * client.print(“o”);*
    * }*

    * }*

    * client.println("

  • ");*
    * }*
    * client.println("
");*
}
void printTwoDigits( uint8_t v) {
* //char str[3];*
* str[0] = ‘0’ + v/10;*
* str[1] = ‘0’ + v % 10;*
* str[2] = 0;*
* //client.print(str);*
}

Working fine here !

With all those smiley faces? Really? I have my doubts.

Héhé !

Like that its will be better .

Thanks

/*
 Web Server
 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield. 
created 18 Dec 2009
 by David A. Mellis
 modified 4 Sep 2010
 by Tom Igoe
*/
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,0, 101);
// Initialize the Ethernet server library with the IP address and port you want to use (port 80 is default for HTTP):
EthernetServer server(80);

 // include the SD library:
#include <SD.h>
//#include <SdFat.h>
SdFile file;
char str[3];

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// store error strings in flash to save RAM
#define error(s) error_P(PSTR(s))
 
void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

// change this to match your SD shield or module, Arduino Ethernet shield: pin 4
const int chipSelect = 4;  

void setup()
{
  pinMode(10, OUTPUT);                       // set the SS pin as an output (necessary!)
  digitalWrite(10, HIGH);                    // but turn off the W5100 chip!
  Serial.begin(9600);
 
 if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!");
 
  // initialize a FAT volume
  if (!volume.init(&card)) error("vol.init failed!");
 
  PgmPrint("Volume is FAT");
  Serial.println(volume.fatType(),DEC);
  Serial.println();
 
  if (!root.openRoot(&volume)) error("openRoot failed");
 
  // list file in root with date and size
  PgmPrintln("Files found in root:");
  root.ls(LS_DATE | LS_SIZE);
  Serial.println();
 
  // Recursive list of all directories
  PgmPrintln("Files found in all dirs:");
  root.ls(LS_R);
 
  Serial.println();
  PgmPrintln("Done");
 
 
  Ethernet.begin(mac, ip);  // start the Ethernet connection and the server:
 //  Ethernet.begin(mac);  // DHCP start the Ethernet connection and the server:
  server.begin();
}

#define BUFSIZ 100
void loop()
{
  char clientline[BUFSIZ];
  int index = 0;
  
  EthernetClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    boolean current_line_is_blank = true;
    
    // reset the input buffer
    index = 0;
    
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        
        // If it isn't a new line, add the character to the buffer
        if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          // are we too big for the buffer? start tossing out data
          if (index >= BUFSIZ) 
            index = BUFSIZ -1;
          
          // continue to read more data!
          continue;
        }
        
        // got a \n or \r new line, which means the string is done
        clientline[index] = 0;
        
        // Print it out for debugging
        Serial.println(clientline);
        
        // Look for substring such as a request to get the root file
        if (strstr(clientline, "GET / ") != 0) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          
          // print all the files, use a helper to keep it clean
          client.println("<h2>Files:</h2>");
          ListFiles(client, LS_SIZE);
        } else if (strstr(clientline, "GET /") != 0) {
          // this time no space after the /, so a sub-file!
          char *filename;
          
          filename = clientline + 5; // look after the "GET /" (5 chars)
          // a little trick, look for the " HTTP/1.1" string and 
          // turn the first character of the substring into a 0 to clear it out.
          (strstr(clientline, " HTTP"))[0] = 0;
          
          // print the file we want
          Serial.println(filename);

          if (! file.open(&root, filename, O_READ)) {
            client.println("HTTP/1.1 404 Not Found");
            client.println("Content-Type: text/html");
            client.println();
            client.println("<h2>File Not Found!</h2>");
            break;
          }
          
          Serial.println("Opened!");
                    
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/octetstream");
          client.print("Content-Disposition: attachment; filename=");
          client.println(filename);
          client.println();
          
          int16_t c;
          while ((c = file.read()) > 0) {
              // uncomment the serial to debug (slow!)
              //Serial.print((char)c);
              client.print((char)c);
          }
          file.close();
        } else {
          // everything else is a 404
          client.println("HTTP/1.1 404 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>File Not Found!</h2>");
        }
        break;
      }
    }
    // give the web browser time to receive the data
    delay(1);
    client.stop();
  }
}

void ListFiles(EthernetClient client, uint8_t flags) {
  // This code is just copied from SdFile.cpp in the SDFat library
  // and tweaked to print to the client output in html!
  dir_t p;
 
  root.rewind();
  client.println("<ul>");
  while (root.readDir(p) > 0) {
    // done if past last used entry
    if (p.name[0] == DIR_NAME_FREE) break;
 
    // skip deleted entry and entries for . and  ..
    if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue;
 
    // only list subdirectories and files
    if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;
 
    // print any indent spaces
    client.print("<li><a href=\"");
    for (uint8_t i = 0; i < 11; i++) {
      if (p.name[i] == ' ') continue;
      if (i == 8) {
        client.print('.');
      }
      client.write(p.name[i]);
    }
    client.print("\">");
 
    // print file name with possible blank fill
    for (uint8_t i = 0; i < 11; i++) {
      if (p.name[i] == ' ') continue;
      if (i == 8) {
        client.print('.');
      }
      client.write(p.name[i]);
    }
 
    client.print("</a>");
 
    if (DIR_IS_SUBDIR(&p)) {
      client.print('/');
    }
 
    // print modify date/time if requested
    if (flags & LS_DATE) {
     // uint16_t fatDate;
     // uint16_t fatTime;
       client.print(' ');
       client.print(FAT_YEAR(p.lastWriteDate));
       client.print('-');
       printTwoDigits(FAT_MONTH(p.lastWriteDate));
       client.print(str);
       client.print('-');
       printTwoDigits(FAT_DAY(p.lastWriteDate));
       client.print(str);
       client.print(' ');
       printTwoDigits(FAT_HOUR(p.lastWriteTime));
       client.print(str);
       client.print(':');
       printTwoDigits(FAT_MINUTE(p.lastWriteTime));
       client.print(str);
       client.print(':');
       printTwoDigits(FAT_SECOND(p.lastWriteTime));
       client.print(str);
          
    }
    // print size if requested
    float Size =p.fileSize;
    if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) {
      client.print(' ');
      client.print("SIZE : ");
     
     if (p.fileSize > 1048576){
       Size = Size/1048576;
       client.print(Size,2);
       client.print("Mo"); 
      }
     
      else if (p.fileSize > 1024){
        Size = Size/1024;
        client.print(Size,2);
        client.print("Ko"); 
      }
      else{
        client.print(p.fileSize);
        client.print("o"); 
      }
      
    }
   

    
    client.println("</li>");
  }
  client.println("</ul>");
}
void printTwoDigits( uint8_t v) {
  //char str[3];
  str[0] = '0' + v/10;
  str[1] = '0' + v % 10;
  str[2] = 0;
  //client.print(str);
}

nikko_net:
Héhé !

Like that its will be better .

Thanks

Sorry to hijack this thread,I want to do exactly the same thing as the OP, this code works almost perfectly. Only that when I click on a link (.jpg for eg) it downloads a 50kb file that wont open. How do I fix that?

Thanks

Bonjour, bonjour,

I think that you must change the content type ??

when file ok :

Serial.println("Opened!");

client.println("HTTP/1.1 200 OK");

test here the .xxx of the file to make the good content type.

client.println("Content-Type: application/octetstream");
client.print("Content-Disposition: attachment; filename=");
client.println(filename);
client.println();

With something like that :

client.println("HTTP/1.1 200 OK");
if (strstr(filename, ".htm") != 0)
client.println("Content-Type: text/html");
else if (strstr(filename, ".jpg") != 0)
client.println("Content-Type: image/jpeg");
else if (strstr(filename, ".gif") != 0)
client.println("Content-Type: image/gif");
else if (strstr(filename, ".3gp") != 0)
client.println("Content-Type: video/mpeg");
else
client.println("Content-Type: text");
client.println();

Thanks,
/N

Hi All, I got it working after changing some code here and there after reading through all resources in arduino.cc, more like trial and error.A friend helped as well. here’s the complete code. Thanks everyone for the help.

#include <SPI.h>
#include <SD.h>
#include <SdFatUtil.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(10,34,37,238);
// Initialize the Ethernet server library with the IP address and port you want to use (port 80 is default for HTTP):
EthernetServer server(88);


//#include <SdFat.h>
// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

// store error strings in flash to save RAM
#define error(s) error_P(PSTR(s))
 
void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

// change this to match your SD shield or module, Arduino Ethernet shield: pin 4
//const int chipSelect = 4;  

void setup() {
  Serial.begin(115200);

  PgmPrint("Free RAM: ");
  Serial.println(FreeRam());  
  
  // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  // breadboards.  use SPI_FULL_SPEED for better performance.
  pinMode(10, OUTPUT);                       // set the SS pin as an output (necessary!)
  digitalWrite(10, HIGH);                    // but turn off the W5100 chip!

  if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!");
  
  // initialize a FAT volume
  if (!volume.init(&card)) error("vol.init failed!");

  PgmPrint("Volume is FAT");
  Serial.println(volume.fatType(),DEC);
  Serial.println();
  
  if (!root.openRoot(&volume)) error("openRoot failed");

  // list file in root with date and size
  PgmPrintln("Files found in root:");
  root.ls(LS_DATE | LS_SIZE);
  Serial.println();
    
  // Recursive list of all directories
  PgmPrintln("Files found in all dirs:");
  root.ls(LS_R);
  
  Serial.println();
  PgmPrintln("Done");
    
  // Debugging complete, we start the server!
  Ethernet.begin(mac, ip);
  server.begin();
}

#define BUFSIZ 100

void loop()
{
  char clientline[BUFSIZ];
  char *filename;
  int index = 0;
  int image = 0;
  
  EthernetClient client = server.available();
  
  
  if (client) {
    // an http request ends with a blank line
    boolean current_line_is_blank = true;
    
    // reset the input buffer
    index = 0;
    
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        
        // If it isn't a new line, add the character to the buffer
        if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          // are we too big for the buffer? start tossing out data
          if (index >= BUFSIZ)
            index = BUFSIZ -1;
            
          // continue to read more data!
          continue;
        }
        
        // got a \n or \r new line, which means the string is done
        clientline[index] = 0;
        filename = 0;
        
		// Print it out for debugging
        Serial.println(clientline);
        
        // Look for substring such as a request to get the root file
        if (strstr(clientline, "GET / ") != 0) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          
          // print all the files, use a helper to keep it clean
          client.println("<h2>Files:</h2>");
          ListFiles(client, LS_SIZE);
        }
		  
		  else if (strstr(clientline, "GET /") != 0) {
          // this time no space after the /, so a sub-file
          
          if (!filename) filename = clientline + 5; // look after the "GET /" (5 chars)
          // a little trick, look for the " HTTP/1.1" string and
          // turn the first character of the substring into a 0 to clear it out.
          (strstr(clientline, " HTTP"))[0] = 0;
          
          // print the file we want
          Serial.println(filename);
          
          if (! file.open(&root, filename, O_READ)) {
            client.println("HTTP/1.1 404 Not Found");
            client.println("Content-Type: text/html");
            client.println();
            client.println("<h2>File Not Found!</h2>");
            break;
          }
          
          Serial.println("Opened!");
          
          client.println("HTTP/1.1 200 OK");
          if (strstr(filename, ".htm") != 0)
             client.println("Content-Type: text/html");
         else if (strstr(filename, ".css") != 0)
             client.println("Content-Type: text/css");
         else if (strstr(filename, ".png") != 0)
             client.println("Content-Type: image/png");
          else if (strstr(filename, ".jpg") != 0)
             client.println("Content-Type: image/jpeg");
         else if (strstr(filename, ".gif") != 0)
             client.println("Content-Type: image/gif");
         else if (strstr(filename, ".3gp") != 0)
             client.println("Content-Type: video/mpeg");
         else if (strstr(filename, ".pdf") != 0)
             client.println("Content-Type: application/pdf");
         else if (strstr(filename, ".js") != 0)
             client.println("Content-Type: application/x-javascript");
         else if (strstr(filename, ".xml") != 0)
             client.println("Content-Type: application/xml");
         else
             client.println("Content-Type: text");

          client.println();
          
          int16_t c;
          while ((c = file.read()) >= 0) {
              // uncomment the serial to debug (slow!)
              //Serial.print((char)c);
              client.print((char)c);
          }
          file.close();
        } else {
          // everything else is a 404
          client.println("HTTP/1.1 404 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>File Not Found!</h2>");
           }
        break;
      }
    }
    // give the web browser time to receive the data
    delay(1);
    client.stop();
  }
}

void ListFiles(EthernetClient client, uint8_t flags) {
  // This code is just copied from SdFile.cpp in the SDFat library
  // and tweaked to print to the client output in html!
  
  dir_t p;
  char str[3];
  root.rewind();
  client.println("<ul>");
  while (root.readDir(p) > 0) {
    // done if past last used entry
    if (p.name[0] == DIR_NAME_FREE) break;
 
    // skip deleted entry and entries for . and  ..
    if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue;
 
    // only list subdirectories and files
    if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;
 
    // print any indent spaces
    client.print("<li><a href=\"");
    for (uint8_t i = 0; i < 11; i++) {
      if (p.name[i] == ' ') continue;
      if (i == 8) {
        client.print('.');
      }
      client.write(p.name[i]);
    }
    client.print("\">");
 
    // print file name with possible blank fill
    for (uint8_t i = 0; i < 11; i++) {
      if (p.name[i] == ' ') continue;
      if (i == 8) {
        client.print('.');
      }
      client.write(p.name[i]);
    }
 
    client.print("</a>");
 
    if (DIR_IS_SUBDIR(&p)) {
      client.print('/');
    }
 
    // print modify date/time if requested
    if (flags & LS_DATE) {
     // uint16_t fatDate;
     // uint16_t fatTime;
       client.print(' ');
       client.print(FAT_YEAR(p.lastWriteDate));
       client.print('-');
       printTwoDigits(FAT_MONTH(p.lastWriteDate));
       client.print(str);
       client.print('-');
       printTwoDigits(FAT_DAY(p.lastWriteDate));
       client.print(str);
       client.print(' ');
       printTwoDigits(FAT_HOUR(p.lastWriteTime));
       client.print(str);
       client.print(':');
       printTwoDigits(FAT_MINUTE(p.lastWriteTime));
       client.print(str);
       client.print(':');
       printTwoDigits(FAT_SECOND(p.lastWriteTime));
       client.print(str);
          
    }
    // print size if requested
    float Size =p.fileSize;
    if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) {
      client.print(' ');
      client.print("SIZE : ");
     
     if (p.fileSize > 1048576){
       Size = Size/1048576;
       client.print(Size,2);
       client.print("Mo"); 
      }
     
      else if (p.fileSize > 1024){
        Size = Size/1024;
        client.print(Size,2);
        client.print("Ko"); 
      }
      else{
        client.print(p.fileSize);
        client.print("o"); 
      }
      
    }
   

    
    client.println("</li>");
  }
  client.println("</ul>");
}
void printTwoDigits( uint8_t v) {
  char str[3];
  str[0] = '0' + v/10;
  str[1] = '0' + v % 10;
  str[2] = 0;
  //client.print(str);
}

/code]