Solved

Upload gif/jpg file in cgi\perl

Posted on 1997-06-16
5
916 Views
Last Modified: 2013-11-18
Hi,
I need a cgi in perl that recive from client (by HTML form) uploaded gif/jpg file and save it on the server.
As a resule,the cgi file will show the client HTML with the gif/jpg picture.
0
Comment
Question by:uriba
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 5

Expert Comment

by:julio011597
ID: 1204275
This is worth more than 50 points, since binary data travels encoded, so you have to:

1. read_from_the_form | decode_someway | store_to_file
2. open_file_for_read | send_back_with_appropriate_headers

Bye, julio
0
 

Author Comment

by:uriba
ID: 1204276
Actually I know how to receive the input string from the client(hml  form).
I know how to save it, and send it back inside  html form back to the client.
But the problem is to parse the input string that contain the all the information about the file(path, name and the file content).

Thank you for the help,
Uri.
0
 

Author Comment

by:uriba
ID: 1204277
Adjusted points to 100
0
 

Expert Comment

by:Sunil
ID: 1204278
email me at someone@inta.net.au and I will send you some files...
0
 

Accepted Solution

by:
Sunil earned 100 total points
ID: 1204279
I emailed you earlier today with the scripts...

Call this Upload.cgi
#################################################
#!/usr/local/bin/perl
# This requires perl 5 I think.

require 'CGI_LIB.pl';
&Parse_Multi;

$File_Name = $CGI{'UploadedFile'}->{'filename'};
# $File_Name is the name of the file.


#
# This will save the file in the current directory.
# If you want to change it simply put the path before $File_Name
# e.g
#
# open(TMP, ">/usr/home/users/$File_Name");


  open(TMP, ">$File_Name");
  binmode(TMP);
  print TMP $CGI{'UploadedFile'}->{'Contents'};
  close(TMP);


#Change this URL as you please
print "Location: http://www.xxxxxxx.com/$File_Name\n\n";

exit;


#################################################################

This is CGI_LIB.pl
#########################################################




#
# CGI_LIB.pl    : Perl Routines to Manipulate CGI input.
# Author        : Simon Tneoh Chee-Boon
# Email         : tneoh@hotmail.com or tneohcb@hitech.com.my
# Last modified : 31st.Jan.1997
# Homepage      : http://140.114.63.14:6083/doc/upload.html
# Changes       : Multiple value is ok now. (For example: "multiple
#                 select form")
#                 New way to store uploaded file's data and works for
#                 both "windows" and "unix" platforms.
# Usage         :
#
# Use this library, of course:
#       require 'CGI_LIB.pl';
#   * If your CGI_LIB.pl is not inside @INC directories. You can do
#     the followings:
#     1) #!/usr/bin/perl -I/dir/where/this/lib/file/saved
#     2) Add the directory to the environment variable "PERL5LIB".
#
# Print the "Content-Type: text/html\n\n":
#       &Print_Head;
#
# For both "GET" and "POST" methods, all data will be parsed into %CGI.
# EG: Single value => <input type="text" name="TextVar" value="123">
#     $CGI{'TextVar'} is equal to "123".
#     Multiple value => <select multiple name="SelectVar">
#                       <option selected value="Sel1"> Option1
#                       <option selected value="Sel2"> Option2
#                       <option value="Sel3"> Option3
#                       </select>
#     $CGI{'SelectVar'} will be an array.
#     $CGI{'SelectVar'}[0] is equal to "Sel1".
#     $CGI{'SelectVar'}[1] is equal to "Sel2".
#     You can check whether it's an array or not by using:
#     if (ref($CGI{'SelectVar'}) =~ /ARRAY/) ...
#
# For those data with enctype="multipart/form-data" will also be
# parsed into %CGI.
# * Make sure in your form tag same as the followings:
#   <form action="/cgi-bin/uploader.cgi" enctype="multipart/form-data"
#       method="post">
# EG: Normal input type => Data saved in the way same as "GET" and "POST"
#                          methods.
#     File type input   => <input type="file" name="UploadedFile">
#     $CGI{'UploadedFile'} will be a hash array.
#     Normally, "name", "filename", "Content-Type" and "Contents" are
#     fields that exist in $CGI{'UploadedFile'}.
#     If you've uploaded a "image/gif" type file with filename
#     "C:\images\cute.gif". You will have the followings:
#     $CGI{'UploadedFile'}->{'name'} => "UploadedFile".
#     $CGI{'UploadedFile'}->{'filename'} => "C:\images\cute.gif".
#     $CGI{'UploadedFile'}->{'Content-Type'} => "image/gif".
#     $CGI{'UploadedFile'}->{'Contents'} => Contents of the gif file.
#
#     When you want to save the uploaded file into a file:
#     open(TMP, "> /tmp/filename") || die "Error create file: $!";
#     print TMP $CGI{'UploadedFile'}->{'Contents'};
#     close(TMP) || die "Error close filehandle: $!";
#     * If you want to use the filename from
#       $CGI{'UploadedFile'}->{'filename'}, you better check the filename
#       if your web server has server side include or CGI programs can be
#       run in directories other than "/cgi-bin". Filename with suffix
#       ".cgi", ".shtm" etc are dangers to your web server.
#
#     If you want a quick way to know whether file upload ok or not,    
#     create the following HTML file and CGI perl script:
#------------/upload.html------------------------------------------------
#     <html>
#     <head>
#     <title>Testing File Upload CGI_LIB.pl</title>
#     </head>
#     <body>
#     <h2>Testing File Upload CGI_LIB.pl</h2>
#     <hr>
#     <form action="/cgi-bin/uploader.cgi" enctype="multipart/form-data"
#         method="post">
#     <input type="file" name="UploadedFile" size="30">
#     <input type="submit" value="Send">
#     </form>
#     </body>
#     </html>
#-------------END---------------------------------------------------------
#-----------/cgi-bin/uploader.cgi-----------------------------------------
#     #!/usr/bin/perl
#     require 'CGI_LIB.pl';
#     #For those whose server is on windows system, you need the following
#     #three lines.
#     #Thanks to Carlo Maria Piacenti <mc7879@mclink.it> who told me about this.
#     binmode(STDIN);
#     binmode(STDOUT);
#     binmode(STDERR);
#     &Parse_Multi;
#     print "Content-Type: $CGI{'UploadedFile'}->{'Content-Type'}\n\n";
#     print $CGI{'UploadedFile'}->{'Contents'};
#--------------END--------------------------------------------------------
sub Parse_Data {
    local($raw_data,@items,$key,$value);

    $raw_data = &Parse_Method;

    # Split different "NAME" and their values.
    @items = split('&', $raw_data);

    # For each list of "NAME=its_value".
    for (@items) {

        $_ =~ tr/+/ /;
        ($key,$value) = split('=',$_,2);

        # The %xx hex numbers are converted to alphanumeric.
        $key   =~ s/%(..)/pack("C", hex($1))/eg;
        $value =~ s/%(..)/pack("C", hex($1))/eg;
        if (grep(/^$key$/, keys(%CGI))) {
        if (@{$CGI{$key}} > 0) {
            push(@{$CGI{$key}}, "$value");
          }
        else {
          $arrvalue = $CGI{$key};
          undef $CGI{$key};
            $CGI{$key}[0] = $arrvalue;
          push(@{$CGI{$key}}, "$value");
          }
        }
        else {
          $CGI{$key} = $value;
        }
     }
}

sub Print_Head {
    print "Content-Type: text/html\n\n";
}

sub Parse_Multi {
    local($boundary,@pairs,$position);
    local($raw_data,$value,$name,$part);

    $raw_data = &Parse_Method;
    ($boundary = $ENV{CONTENT_TYPE}) =~ s/^.*boundary=(.*)$/\1/;
    @pairs = split(/--$boundary/, $raw_data);
    @pairs = splice(@pairs,1,$#pairs-1);

    for $part (@pairs) {
      $part =~ s/[\r]\n$//g;
      ($dump, $firstline, $datas) = split(/[\r]\n/, $part, 3);
      next if $firstline =~ /filename=\"\"/;
      $firstline =~ s/^Content-Disposition: form-data; //;
      (@columns) = split(/;\s+/, $firstline);
      ($name = $columns[0]) =~ s/^name="([^"]+)"$/\1/g;
      if ($#columns > 0) {
      if ($datas =~ /^Content-Type:/) {
        ($CGI{"$name"}->{'Content-Type'}, $blankline, $datas) = split(/[\r]\n/, $datas, 3);
          $CGI{"$name"}->{'Content-Type'} =~ s/^Content-Type: ([^\s]+)$/\1/g;
      }
      else {
        ($blankline, $datas) = split(/[\r]\n/, $datas, 2);
        $CGI{"$name"}->{'Content-Type'} = "application/octet-stream";
      }
      }
      else {
      ($blankline, $datas) = split(/[\r]\n/, $datas, 2);
        if (grep(/^$name$/, keys(%CGI))) {
          if (@{$CGI{$name}} > 0) {
            push(@{$CGI{$name}}, $datas);
          }
          else {
            $arrvalue = $CGI{$name};
            undef $CGI{$name};
            $CGI{$name}[0] = $arrvalue;
            push(@{$CGI{$name}}, $datas);
          }
        }
        else {
        next if $datas =~ /^\s*$/;
          $CGI{"$name"} = $datas;
        }
        next;
      }
      for $currentColumn (@columns) {
        ($currentHeader, $currentValue) = $currentColumn =~ /^([^=]+)="([^"]+)"$/;
        $CGI{"$name"}->{"$currentHeader"} = $currentValue;
        $CGI{"$name"}->{"$currentHeader"} =~ s/^.*(\\|\/)([^\\\/]+)$/\2/g if $currentHeader eq "filename";
      }
      $CGI{"$name"}->{'Contents'} = $datas;
    }
}

sub Parse_Method {
    local($buffer);

    if ($ENV{'REQUEST_METHOD'} eq "POST") {
      read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
      return $buffer;
    }
    elsif ($ENV{'REQUEST_METHOD'} eq "GET") {
      return $ENV{'QUERY_STRING'};
    }
    else {
      return 0;
    }
}
#END of CGI_LIB.pl library.
1;
__END__



0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface In the first article: A Better Website Login System (http://www.experts-exchange.com/A_2902.html) I introduced the EE Collaborative Login System and its intended purpose. In this article I will discuss some of the design consideratio…
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question