Перейти к содержанию

Upload from WEB


Рекомендуемые сообщения

  • 2 недели спустя...

CREATING A FILE UPLOAD FIELD

print $query->filefield(-name=>'uploaded_file',

-default=>'starting value',

-size=>50,

-maxlength=>80);

-or-

print $query->filefield('uploaded_file','starting value',50,80);

filefield() will return a file upload field for Netscape 2.0 browsers. In order to take full advantage of this you must use the new multipart encoding scheme for the form. You can do this either by calling start_form() with an encoding type of &CGI::MULTIPART, or by calling the new method start_multipart_form() instead of vanilla start_form().

Parameters

The first parameter is the required name for the field (-name).

The optional second parameter is the starting value for the field contents to be used as the default file name (-default).

For security reasons, browsers don't pay any attention to this field, and so the starting value will always be blank. Worse, the field loses its ``sticky'' behavior and forgets its previous contents. The starting value field is called for in the HTML specification, however, and possibly some browser will eventually provide support for it.

The optional third parameter is the size of the field in characters (-size).

The optional fourth parameter is the maximum number of characters the field will accept (-maxlength).

When the form is processed, you can retrieve the entered filename by calling param():

$filename = $query->param('uploaded_file');

Different browsers will return slightly different things for the name. Some browsers return the filename only. Others return the full path to the file, using the path conventions of the user's machine. Regardless, the name returned is always the name of the file on the user's machine, and is unrelated to the name of the temporary file that CGI.pm creates during upload spooling (see below).

The filename returned is also a file handle. You can read the contents of the file using standard Perl file reading calls:

# Read a text file and print it out

while (<$filename>) {

print;

}

# Copy a binary file to somewhere safe

open (OUTFILE,">>/usr/local/web/users/feedback");

while ($bytesread=read($filename,$buffer,1024)) {

print OUTFILE $buffer;

}

However, there are problems with the dual nature of the upload fields. If you use strict, then Perl will complain when you try to use a string as a filehandle. You can get around this by placing the file reading code in a block containing the no strict pragma. More seriously, it is possible for the remote user to type garbage into the upload field, in which case what you get from param() is not a filehandle at all, but a string.

To be safe, use the upload() function (new in version 2.47). When called with the name of an upload field, upload() returns a filehandle, or undef if the parameter is not a valid filehandle.

$fh = $query->upload('uploaded_file');

while (<$fh>) {

print;

}

This is the recommended idiom.

When a file is uploaded the browser usually sends along some information along with it in the format of headers. The information usually includes the MIME content type. Future browsers may send other information as well (such as modification date and size). To retrieve this information, call uploadInfo(). It returns a reference to an associative array containing all the document headers.

$filename = $query->param('uploaded_file');

$type = $query->uploadInfo($filename)->{'Content-Type'};

unless ($type eq 'text/html') {

die "HTML FILES ONLY!";

}

If you are using a machine that recognizes ``text'' and ``binary'' data modes, be sure to understand when and how to use them (see the Camel book). Otherwise you may find that binary files are corrupted during file uploads.

There are occasionally problems involving parsing the uploaded file. This usually happens when the user presses ``Stop'' before the upload is finished. In this case, CGI.pm will return undef for the name of the uploaded file and set cgi_error() to the string ``400 Bad request (malformed multipart POST)''. This error message is designed so that you can incorporate it into a status code to be sent to the browser. Example:

$file = $query->upload('uploaded_file');

if (!$file && $query->cgi_error) {

print $query->header(-status=>$query->cgi_error);

exit 0;

}

You are free to create a custom HTML page to complain about the error, if you wish.

JAVASCRIPTING: The -onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut and -onSelect parameters are recognized. See textfield() for details.

Ссылка на комментарий
Поделиться на другие сайты

CREATING A FILE UPLOAD FIELD

print $query->filefield(-name=>'uploaded_file',

-default=>'starting value',

-size=>50,

-maxlength=>80);

-or-

print $query->filefield('uploaded_file','starting value',50,80);

filefield() will return a file upload field for Netscape 2.0 browsers. In order to take full advantage of this you must use the new multipart encoding scheme for the form. You can do this either by calling start_form() with an encoding type of &CGI::MULTIPART, or by calling the new method start_multipart_form() instead of vanilla start_form().

Parameters

The first parameter is the required name for the field (-name).

The optional second parameter is the starting value for the field contents to be used as the default file name (-default).

For security reasons, browsers don't pay any attention to this field, and so the starting value will always be blank. Worse, the field loses its ``sticky'' behavior and forgets its previous contents. The starting value field is called for in the HTML specification, however, and possibly some browser will eventually provide support for it.

The optional third parameter is the size of the field in characters (-size).

The optional fourth parameter is the maximum number of characters the field will accept (-maxlength).

When the form is processed, you can retrieve the entered filename by calling param():

$filename = $query->param('uploaded_file');

Different browsers will return slightly different things for the name. Some browsers return the filename only. Others return the full path to the file, using the path conventions of the user's machine. Regardless, the name returned is always the name of the file on the user's machine, and is unrelated to the name of the temporary file that CGI.pm creates during upload spooling (see below).

The filename returned is also a file handle. You can read the contents of the file using standard Perl file reading calls:

# Read a text file and print it out

while (<$filename>) {

print;

}

# Copy a binary file to somewhere safe

open (OUTFILE,">>/usr/local/web/users/feedback");

while ($bytesread=read($filename,$buffer,1024)) {

print OUTFILE $buffer;

}

However, there are problems with the dual nature of the upload fields. If you use strict, then Perl will complain when you try to use a string as a filehandle. You can get around this by placing the file reading code in a block containing the no strict pragma. More seriously, it is possible for the remote user to type garbage into the upload field, in which case what you get from param() is not a filehandle at all, but a string.

To be safe, use the upload() function (new in version 2.47). When called with the name of an upload field, upload() returns a filehandle, or undef if the parameter is not a valid filehandle.

$fh = $query->upload('uploaded_file');

while (<$fh>) {

print;

}

This is the recommended idiom.

When a file is uploaded the browser usually sends along some information along with it in the format of headers. The information usually includes the MIME content type. Future browsers may send other information as well (such as modification date and size). To retrieve this information, call uploadInfo(). It returns a reference to an associative array containing all the document headers.

$filename = $query->param('uploaded_file');

$type = $query->uploadInfo($filename)->{'Content-Type'};

unless ($type eq 'text/html') {

die "HTML FILES ONLY!";

}

If you are using a machine that recognizes ``text'' and ``binary'' data modes, be sure to understand when and how to use them (see the Camel book). Otherwise you may find that binary files are corrupted during file uploads.

There are occasionally problems involving parsing the uploaded file. This usually happens when the user presses ``Stop'' before the upload is finished. In this case, CGI.pm will return undef for the name of the uploaded file and set cgi_error() to the string ``400 Bad request (malformed multipart POST)''. This error message is designed so that you can incorporate it into a status code to be sent to the browser. Example:

$file = $query->upload('uploaded_file');

if (!$file && $query->cgi_error) {

print $query->header(-status=>$query->cgi_error);

exit 0;

}

You are free to create a custom HTML page to complain about the error, if you wish.

JAVASCRIPTING: The -onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut and -onSelect parameters are recognized. See textfield() for details.

Ссылка на комментарий
Поделиться на другие сайты

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.

Гость
Ответить в этой теме...

×   Вставлено с форматированием.   Вставить как обычный текст

  Разрешено использовать не более 75 эмодзи.

×   Ваша ссылка была автоматически встроена.   Отображать как обычную ссылку

×   Ваш предыдущий контент был восстановлен.   Очистить редактор

×   Вы не можете вставлять изображения напрямую. Загружайте или вставляйте изображения по ссылке.

Загрузка...
×
×
  • Создать...