Upload file data error there is no uploaded file associated with the given key

Upload file data error there is no uploaded file associated with the given key $_FILES and $_POST will return empty Clarification on the MAX_FILE_SIZE hidden form field and the UPLOAD_ERR_FORM_SIZE error code: PHP has the somewhat strange feature of checking multiple «maximum file sizes». The two widely known limits are the php.ini settings «post_max_size» […]

Содержание

  1. Upload file data error there is no uploaded file associated with the given key
  2. is_uploaded_file
  3. Description
  4. Parameters
  5. Return Values
  6. Examples
  7. See Also
  8. User Contributed Notes 14 notes
  9. The Joomla! Forum™
  10. There was an error uploading this file to the server
  11. There was an error uploading this file to the server
  12. Re: There was an error uploading this file to the server
  13. Re: There was an error uploading this file to the server
  14. Re: There was an error uploading this file to the server
  15. Re: There was an error uploading this file to the server
  16. Re: There was an error uploading this file to the server
  17. Re: There was an error uploading this file to the server
  18. Re: There was an error uploading this file to the server
  19. Re: There was an error uploading this file to the server
  20. Re: There was an error uploading this file to the server
  21. Re: There was an error uploading this file to the server
  22. Re: There was an error uploading this file to the server
  23. Re: There was an error uploading this file to the server
  24. Re: There was an error uploading this file to the server
  25. Re: There was an error uploading this file to the server

Upload file data error there is no uploaded file associated with the given key

$_FILES and $_POST will return empty

Clarification on the MAX_FILE_SIZE hidden form field and the UPLOAD_ERR_FORM_SIZE error code:

PHP has the somewhat strange feature of checking multiple «maximum file sizes».

The two widely known limits are the php.ini settings «post_max_size» and «upload_max_size», which in combination impose a hard limit on the maximum amount of data that can be received.

In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names «max_file_size» (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.

The PHP documentation also makes (or made — see bug #40387 — http://bugs.php.net/bug.php?id=40387) vague references to «allows browsers to check the file size before uploading». This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big — this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).

When uploading a file, it is common to visit the php.ini and set up upload_tmp_dir = /temp but in the case of some web hostess as fatcow you need to direct not only /tmp but upload_tmp_dir = /hermes/walnaweb13a/b345/moo.youruser/tmp

If not the $_FILES show you an error #6 «Missing a temporary folder

I have expanded @adam at gotlinux dot us’s example a bit with proper UPLOAD_FOO constants and gettext support. Also UPLOAD_ERR_EXTENSION is added (was missing in his version). Hope this helps someone.

class Some <
/**
* Upload error codes
* @var array
*/
private static $upload_errors = [];

public function __construct () <
// Init upload errors
self :: $upload_errors = [
UPLOAD_ERR_OK => _ ( ‘There is no error, the file uploaded with success.’ ),
UPLOAD_ERR_INI_SIZE => _ ( ‘The uploaded file exceeds the upload_max_filesize directive in php.ini.’ ),
UPLOAD_ERR_FORM_SIZE => _ ( ‘The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.’ ),
UPLOAD_ERR_PARTIAL => _ ( ‘The uploaded file was only partially uploaded.’ ),
UPLOAD_ERR_NO_FILE => _ ( ‘No file was uploaded.’ ),
UPLOAD_ERR_NO_TMP_DIR => _ ( ‘Missing a temporary folder.’ ),
UPLOAD_ERR_CANT_WRITE => _ ( ‘Cannot write to target directory. Please fix CHMOD.’ ),
UPLOAD_ERR_EXTENSION => _ ( ‘A PHP extension stopped the file upload.’ ),
];
>
>
?>

One thing that is annoying is that the way these constant values are handled requires processing no error with the equality, which wastes a little bit of space. Even though «no error» is 0, which typically evaluates to «false» in an if statement, it will always evaluate to true in this context.

So, instead of this:
——
if( $_FILES [ ‘userfile’ ][ ‘error’ ]) <
// handle the error
> else <
// process
>
?>
——
You have to do this:
——
if( $_FILES [ ‘userfile’ ][ ‘error’ ]== 0 ) <
// process
> else <
// handle the error
>
?>
——
Also, ctype_digit fails, but is_int works. If you’re wondering. no, it doesn’t make any sense.

You ask the question: Why make stuff complicated when you can make it easy? I ask the same question since the version of the code you / Anonymous / Thalent (per danbrown) have posted is unnecessary overhead and would result in a function call, as well as a potentially lengthy switch statement. In a loop, that would be deadly. try this instead:

——
= array(
1 => ‘The uploaded file exceeds the upload_max_filesize directive in php.ini.’ ,
‘The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.’ ,
‘The uploaded file was only partially uploaded.’ ,
‘No file was uploaded.’ ,
6 => ‘Missing a temporary folder.’ ,
‘Failed to write file to disk.’ ,
‘A PHP extension stopped the file upload.’
);

// Outside a loop.
if( $_FILES [ ‘userfile’ ][ ‘error’ ]== 0 ) <
// process
> else <
$error_message = $error_types [ $_FILES [ ‘userfile’ ][ ‘error’ ]];
// do whatever with the error message
>

// In a loop.
for( $x = 0 , $y = count ( $_FILES [ ‘userfile’ ][ ‘error’ ]); $x $y ;++ $x ) <
if( $_FILES [ ‘userfile’ ][ ‘error’ ][ $x ]== 0 ) <
// process
> else <
$error_message = $error_types [ $_FILES [ ‘userfile’ ][ ‘error’ ][ $x ]];
// Do whatever with the error message
>
>

// When you’re done. if you aren’t doing all of this in a function that’s about to end / complete all the processing and want to reclaim the memory
unset( $error_types );
?>

Источник

is_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

is_uploaded_file — Tells whether the file was uploaded via HTTP POST

Description

Returns true if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn’t tried to trick the script into working on files upon which it should not be working—for instance, /etc/passwd .

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

For proper working, the function is_uploaded_file() needs an argument like $_FILES[‘userfile’][‘tmp_name’] , — the name of the uploaded file on the client’s machine $_FILES[‘userfile’][‘name’] does not work.

Parameters

The filename being checked.

Return Values

Returns true on success or false on failure.

Examples

Example #1 is_uploaded_file() example

if ( is_uploaded_file ( $_FILES [ ‘userfile’ ][ ‘tmp_name’ ])) <
echo «File » . $_FILES [ ‘userfile’ ][ ‘name’ ] . » uploaded successfully.n» ;
echo «Displaying contentsn» ;
readfile ( $_FILES [ ‘userfile’ ][ ‘tmp_name’ ]);
> else <
echo «Possible file upload attack: » ;
echo «filename ‘» . $_FILES [ ‘userfile’ ][ ‘tmp_name’ ] . «‘.» ;
>

See Also

  • move_uploaded_file() — Moves an uploaded file to a new location
  • $_FILES
  • See Handling file uploads for a simple usage example.

User Contributed Notes 14 notes

Note that calling this function before move_uploaded_file() is not necessary, as it does the exact same checks already. It provides no extra security. Only when you’re trying to use an uploaded file for something other than moving it to a new location.

To expand on what nicoSWD stated about this function.

Any script working with the temporary file $_FILES[][‘tmp_name’] should call this function.

In any case where the script is modified to unlink(), rename() or otherwise modify the file that IS NOT move_uploaded_file() will not have the upload checked.

Likewise, most file operations are cached in PHP, therefore there should be minimal performance hit running is_uploaded_file before move_uploaded_file, since it will usually used a cached result for the latter.

The security benefits outweigh the microsecond difference in performance in any event, and should universally be used as soon as the $_FILES array is first entered into an application. While there may not be an immediate issue, code evolves and could quickly change this fact.

As of PHP 4.2.0, rather than automatically assuming a failed file uploaded is a file attack, you can use the error code associated with the file upload to check and see why the upload failed. This error code is stored in the userfile array (ex: $HTTP_POST_FILES[‘userfile’][‘error’]).

Here’s an example of a switch:

//include code to copy tmp file to final location here.

>else <
switch($HTTP_POST_FILES[‘userfile’][‘error’]) <
case 0: //no error; possible file attack!
echo «There was a problem with your upload.»;
break;
case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
echo «The file you are trying to upload is too big.»;
break;
case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
echo «The file you are trying to upload is too big.»;
break;
case 3: //uploaded file was only partially uploaded
echo «The file you are trying upload was only partially uploaded.»;
break;
case 4: //no file was uploaded
echo «You must select an image for upload.»;
break;
default: //a default error, just in case! 🙂
echo «There was a problem with your upload.»;
break;
>

Additionally, by testing the ‘name’ element of the file upload array, you can filter out unwanted file types (.exe, .zip, .bat, etc). Here’s an example of a filter that can be added before testing to see if the file was uploaded:

//rejects all .exe, .com, .bat, .zip, .doc and .txt files
if(preg_match(«/.exe$|.com$|.bat$|.zip$|.doc$|.txt$/i», $HTTP_POST_FILES[‘userfile’][‘name’])) <
exit(«You cannot upload this type of file.»);
>

//if file is not rejected by the filter, continue normally
if (is_uploaded_file($userfile)) <

Just looked at what I posted again and found several mistakes of the major and minor sort. That’s what I get for posting before I finish my coffee. This should work better (i.e. should work in the first place):

default: //a default error, just in case! 🙂
echo «There was a problem with your upload.» ;
$err_msg = «Unrecognized file POST error: » . $HTTP_POST_FILES [ ‘userfile’ ][ ‘error’ ];
if (!( strpos ( $err_msg , «n» ) === false )) <
$err_lines = explode ( «n» , $err_msg );
foreach ( $err_lines as $msg ) <
error_log ( $msg , 0 );
>
> else <
error_log ( $err_msg , 0 );
>
break;
?>

It isn’t mentioned anywhere that I’ve seen, but $filename *is* case-sensitive on Windows.
It means that while C:WindowsTEMPphp123.tmp may have been uploaded, C:WindowsTempphp123.tmp was not.

I found this out because I was using realpath() on the filename which ‘fixed’ the case (my Temp folder is in titlecase, not uppercase — thank you Vista).

Anyways, the problem was that PHP used %TEMP% to determine the destination for the uploaded file, and %TEMP% used the all-capitals version of the path. Changing it to use titlecase instead + restarting Apache fixed the problem.

Here is my code for file handler, i hope it help to all:

First a class to handler file upload:
( ‘UPLOAD_PATH’ , ‘upload/’ );
define ( ‘MAXIMUM_FILESIZE’ , ‘10485760’ ); //10 MB
class FileHandler
<
private $file_types = array( ‘xls’ , ‘xlsx’ );
private $files = null ;
private $filename_sanitized = null ;
private $filename_original = null ;

public function __construct ( $files )
<
$this -> files = $files ;
>

public function setFileTypes ( $fileTypes = array())
<
$this -> file_types = $fileTypes ;
return $this ;
>

public function setFileNameOriginal ( $filename )
<
$this -> filename_original = $filename ;
>

public function fileNameOriginal ()
<
return $this -> filename_original ;
>

public function sanitize ( $cursor = 0 )
<
$this -> setFileNameOriginal ( $this -> files [ ‘name’ ][ $cursor ]);

$safe_filename = preg_replace (
array( «/s+/» , «/[^-.w]+/» ),
array( «_» , «» ),
trim ( $this -> fileNameOriginal ()));
$this -> filename_sanitized = md5 ( $safe_filename . time ()). $safe_filename ;
return $this ;
>

public function fileSize ( $cursor = 0 )
<
return $this -> files [ ‘size’ ][ $cursor ];
>

public function extensionValid ()
<
$fileTypes = implode ( ‘|’ , $this -> file_types );
$rEFileTypes = «/^.( $fileTypes )<1>$/i» ;
if(! preg_match ( $rEFileTypes , strrchr ( $this -> filename_sanitized , ‘.’ )))
throw new Exception ( ‘No se pudo encontrar el tipo de archivo apropiado’ );

public function isUploadedFile ( $cursor )
<
if(! is_uploaded_file ( $this -> files [ ‘tmp_name’ ][ $cursor ]))
<
throw new Exception ( «No se obtuvo la carga del archivo» );
>
>

public function saveUploadedFile ( $cursor )
<
if(! move_uploaded_file ( $this -> files [ ‘tmp_name’ ][ $cursor ], UPLOAD_PATH . $this -> filename_sanitized ))
throw new Exception ( «No se consiguió guardar el archivo» );
>

public function fileNameSanitized ()
<
return $this -> filename_sanitized ;
>

public function uploadFile ( $cursor = 0 )
<
$this -> isUploadedFile ( $cursor );
if ( $this -> sanitize ( $cursor )-> fileSize ( $cursor ) MAXIMUM_FILESIZE )
<
$this -> extensionValid ()-> saveUploadedFile ( $cursor );
>
else
<
throw new Exception ( «El archivo es demasiado grande.» );
>
return $name ;
>

?>

Next a part of code to use the class

//form is submited and detect that
if ( $form_submited == 1 )
<
try
<
//i assume de input file is:
/*
[]» name=» []» type=»file»/>
where EXCEL_FILE is the constant:
define(‘EXCEL_FILE’, ‘excel_file’);
*/
$file = new FileHandler ( $_FILES [ ‘excel_file’ ]);
$inputFileName = $file -> uploadFile ()-> fileNameSanitized (); // File to read
.

>
catch( Exception $e )
<
die( ‘Error cargando archivo «‘ .( $file -> fileNameOriginal ()). ‘»: ‘ . $e -> getMessage ());
>

Источник

The Joomla! Forum™

There was an error uploading this file to the server

There was an error uploading this file to the server

Post by envisageBLUE » Sun Mar 23, 2008 4:39 am

I’m getting this error «There was an error uploading this file to the server.» while working on my local host.

I get this error when I’m trying to install anynew template, during upload.

I’ve checked the configuration file and all seems to be OK.

Any ideas anyone?

Cheers for your help
Peter.

Re: There was an error uploading this file to the server

Post by bnecom » Fri Apr 04, 2008 9:08 am

Did you find a fix to this, I am having the same problem and have tried everything.

Re: There was an error uploading this file to the server

Post by envisageBLUE » Sat Apr 05, 2008 12:29 am

No, still having the same problem.

Not sure what to do. still wiaiting.

Re: There was an error uploading this file to the server

Post by fmmarzoa » Fri Apr 11, 2008 4:24 pm

Re: There was an error uploading this file to the server

Post by chac416 » Mon Aug 11, 2008 5:11 pm

Re: There was an error uploading this file to the server

Post by js-15084 » Tue Aug 12, 2008 7:04 am

Re: There was an error uploading this file to the server

Post by EEjoomla » Sun Sep 14, 2008 7:17 am

The most common reason for this problem is that the File you have uploaded is too big.
The File Size Upload Limit on your Server is set too low to allow larger files to be uploaded. By
default PHP allows files up to 2 MB, but you can set to 4 MB to get rid of this error.

If you have access to the php.ini, then change the directive upload_max_filesize to «4M»
and reload the server configuration.

If you are running PHP in CGI mode on Apache, you can place an .htaccess file in your
Joomla! root directory and place the following code inside:

php_value upload_max_filesize 4M

This will solve the problem

Re: There was an error uploading this file to the server

Post by jessiered » Wed Jan 21, 2009 1:47 am

EEjoomla wrote: The most common reason for this problem is that the File you have uploaded is too big.
The File Size Upload Limit on your Server is set too low to allow larger files to be uploaded. By
default PHP allows files up to 2 MB, but you can set to 4 MB to get rid of this error.

If you have access to the php.ini, then change the directive upload_max_filesize to «4M»
and reload the server configuration.

If you are running PHP in CGI mode on Apache, you can place an .htaccess file in your
Joomla! root directory and place the following code inside:

php_value upload_max_filesize 4M

This will solve the problem

Re: There was an error uploading this file to the server

Post by jessiered » Wed Jan 21, 2009 1:49 am

Hi in what section on the php.ini can I find the Upload_max_filesize to «4M»

Thanks in advance?

Re: There was an error uploading this file to the server

Post by jessiered » Wed Jan 21, 2009 1:51 am

Re: There was an error uploading this file to the server

Post by jessiered » Wed Jan 21, 2009 2:01 am

EEjoomla wrote: The most common reason for this problem is that the File you have uploaded is too big.
The File Size Upload Limit on your Server is set too low to allow larger files to be uploaded. By
default PHP allows files up to 2 MB, but you can set to 4 MB to get rid of this error.

If you have access to the php.ini, then change the directive upload_max_filesize to «4M»
and reload the server configuration.

If you are running PHP in CGI mode on Apache, you can place an .htaccess file in your
Joomla! root directory and place the following code inside:

php_value upload_max_filesize 4M

This will solve the problem

Re: There was an error uploading this file to the server

Post by jessiered » Wed Jan 21, 2009 2:02 am

Can this be it or not:

; Maximum size of POST data that PHP will accept.
post_max_size = 8M

Please help.
Thanks in advance

Re: There was an error uploading this file to the server

Post by jessiered » Wed Jan 21, 2009 2:04 am

Hi! I go it! Thanks EEJoomla!

Can I change it to upload_max_filesize to «6M» .

Re: There was an error uploading this file to the server

Post by lilmiss » Thu Feb 26, 2009 5:02 am

Yes you can. I just did to 10M but you can change it to whatever.

****note for Godaddy accounts. I had to make backup copies of the php5.ini. save to my computer. then reupload them and overide the original php5.ini for the changes to appear. When I had made the changes on the serverside only using my FTP. the changes would show on the file but not register.

This is what was stated on Godaddy’s Support Search:

There are two variables within your php.ini file that are responsible for managing user file uploads.

* post_max_size This variable determines the maximum amount of data that PHP will accept in a single form submission using the POST method. Its default value is 8 MB, as shown below:
post_max_size = 8M
* upload_max_filesize This variable limits the size of an individual file uploaded to your site. Its default value is 2 MB, as shown below:
upload_max_filesize = 2M

An increase in the value of these variables expands user file upload limits.

NOTE: After making changes to php.ini, you must perform an httpd restart for them to take effect. This is accomplished by running the following from your command line:
/sbin/service httpd restart

Hope this helps!

Re: There was an error uploading this file to the server

Post by ticonzero » Wed Apr 29, 2009 2:24 pm

EEjoomla wrote: The most common reason for this problem is that the File you have uploaded is too big.
The File Size Upload Limit on your Server is set too low to allow larger files to be uploaded. By
default PHP allows files up to 2 MB, but you can set to 4 MB to get rid of this error.

If you have access to the php.ini, then change the directive upload_max_filesize to «4M»
and reload the server configuration.

If you are running PHP in CGI mode on Apache, you can place an .htaccess file in your
Joomla! root directory and place the following code inside:

Источник

Объяснение сообщений об ошибках

PHP возвращает код ошибки наряду с другими
атрибутами принятого файла. Он расположен в массиве, создаваемом PHP
при загрузке файла, и может быть получен при обращении по ключу
error. Другими словами, код ошибки можно
найти в $_FILES[‘userfile’][‘error’].

UPLOAD_ERR_OK

Значение: 0; Ошибок не возникло, файл был успешно загружен на сервер.

UPLOAD_ERR_INI_SIZE

Значение: 1; Размер принятого файла превысил максимально допустимый
размер, который задан директивой upload_max_filesize
конфигурационного файла php.ini.

UPLOAD_ERR_FORM_SIZE

Значение: 2; Размер загружаемого файла превысил значение MAX_FILE_SIZE,
указанное в HTML-форме.

UPLOAD_ERR_PARTIAL

Значение: 3; Загружаемый файл был получен только частично.

UPLOAD_ERR_NO_FILE

Значение: 4; Файл не был загружен.

UPLOAD_ERR_NO_TMP_DIR

Значение: 6; Отсутствует временная папка.

UPLOAD_ERR_CANT_WRITE

Значение: 7; Не удалось записать файл на диск.

UPLOAD_ERR_EXTENSION

Значение: 8; Модуль PHP остановил загрузку файла. PHP не
предоставляет способа определить, какой модуль остановил
загрузку файла; в этом может помочь просмотр списка загруженных
модулей с помощью phpinfo().

Viktor

8 years ago


Update to Adams old comment.

This is probably useful to someone.

<?php

$phpFileUploadErrors

= array(
   
0 => 'There is no error, the file uploaded with success',
   
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
   
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
   
3 => 'The uploaded file was only partially uploaded',
   
4 => 'No file was uploaded',
   
6 => 'Missing a temporary folder',
   
7 => 'Failed to write file to disk.',
   
8 => 'A PHP extension stopped the file upload.',
);


Anonymous

13 years ago


[EDIT BY danbrown AT php DOT net: This code is a fixed version of a note originally submitted by (Thalent, Michiel Thalen) on 04-Mar-2009.]

This is a handy exception to use when handling upload errors:

<?php
class UploadException extends Exception

{

    public function
__construct($code) {

       
$message = $this->codeToMessage($code);

       
parent::__construct($message, $code);

    }

    private function

codeToMessage($code)

    {

        switch (
$code) {

            case
UPLOAD_ERR_INI_SIZE:

               
$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";

                break;

            case
UPLOAD_ERR_FORM_SIZE:

               
$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";

                break;

            case
UPLOAD_ERR_PARTIAL:

               
$message = "The uploaded file was only partially uploaded";

                break;

            case
UPLOAD_ERR_NO_FILE:

               
$message = "No file was uploaded";

                break;

            case
UPLOAD_ERR_NO_TMP_DIR:

               
$message = "Missing a temporary folder";

                break;

            case
UPLOAD_ERR_CANT_WRITE:

               
$message = "Failed to write file to disk";

                break;

            case
UPLOAD_ERR_EXTENSION:

               
$message = "File upload stopped by extension";

                break;

            default:

$message = "Unknown upload error";

                break;

        }

        return
$message;

    }

}
// Use

if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {

//uploading successfully done

} else {

throw new
UploadException($_FILES['file']['error']);

}

?>


adam at gotlinux dot us

17 years ago


This is probably useful to someone.

<?php

array(

       
0=>"There is no error, the file uploaded with success",

       
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",

       
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"

       
3=>"The uploaded file was only partially uploaded",

       
4=>"No file was uploaded",

       
6=>"Missing a temporary folder"

);

?>


stephen at poppymedia dot co dot uk

17 years ago


if post is greater than post_max_size set in php.ini

$_FILES and $_POST will return empty


svenr at selfhtml dot org

15 years ago


Clarification on the MAX_FILE_SIZE hidden form field and the UPLOAD_ERR_FORM_SIZE error code:

PHP has the somewhat strange feature of checking multiple "maximum file sizes".

The two widely known limits are the php.ini settings "post_max_size" and "upload_max_size", which in combination impose a hard limit on the maximum amount of data that can be received.

In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names "max_file_size" (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.

The PHP documentation also makes (or made - see bug #40387 - http://bugs.php.net/bug.php?id=40387) vague references to "allows browsers to check the file size before uploading". This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big - this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).


jalcort at att dot net

3 years ago


When uploading a file, it is common to visit the php.ini and set up upload_tmp_dir = /temp but in the case of some web hostess as fatcow you need to direct not only /tmp but upload_tmp_dir = /hermes/walnaweb13a/b345/moo.youruser/tmp

If not the $_FILES show you an error #6 "Missing a temporary folder


roland at REMOVE_ME dot mxchange dot org

4 years ago


I have expanded @adam at gotlinux dot us's example a bit with proper UPLOAD_FOO constants and gettext support. Also UPLOAD_ERR_EXTENSION is added (was missing in his version). Hope this helps someone.

<?php
class Some {
   
/**
     * Upload error codes
     * @var array
     */
   
private static $upload_errors = [];

    public function

__construct() {
       
// Init upload errors
       
self::$upload_errors = [
           
UPLOAD_ERR_OK => _('There is no error, the file uploaded with success.'),
           
UPLOAD_ERR_INI_SIZE => _('The uploaded file exceeds the upload_max_filesize directive in php.ini.'),
           
UPLOAD_ERR_FORM_SIZE => _('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'),
           
UPLOAD_ERR_PARTIAL => _('The uploaded file was only partially uploaded.'),
           
UPLOAD_ERR_NO_FILE => _('No file was uploaded.'),
           
UPLOAD_ERR_NO_TMP_DIR => _('Missing a temporary folder.'),
           
UPLOAD_ERR_CANT_WRITE => _('Cannot write to target directory. Please fix CHMOD.'),
           
UPLOAD_ERR_EXTENSION => _('A PHP extension stopped the file upload.'),
        ];
    }
}
?>


Jeff Miner mrjminer AT gmail DOT com

12 years ago


One thing that is annoying is that the way these constant values are handled requires processing no error with the equality, which wastes a little bit of space.  Even though "no error" is 0, which typically evaluates to "false" in an if statement, it will always evaluate to true in this context.

So, instead of this:

-----

<?php

if($_FILES['userfile']['error']) {

 
// handle the error

} else {

 
// process

}

?>

-----

You have to do this:

-----

<?php

if($_FILES['userfile']['error']==0) {

 
// process

} else {

 
// handle the error

}

?>

-----

Also, ctype_digit fails, but is_int works.  If you're wondering... no, it doesn't make any sense.

To Schoschie:

You ask the question:  Why make stuff complicated when you can make it easy?  I ask the same question since the version of the code you / Anonymous / Thalent (per danbrown) have posted is unnecessary overhead and would result in a function call, as well as a potentially lengthy switch statement.  In a loop, that would be deadly... try this instead:

-----

<?php

$error_types
= array(

1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',

'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',

'The uploaded file was only partially uploaded.',

'No file was uploaded.',

6=>'Missing a temporary folder.',

'Failed to write file to disk.',

'A PHP extension stopped the file upload.'

);
// Outside a loop...

if($_FILES['userfile']['error']==0) {

 
// process

} else {

 
$error_message = $error_types[$_FILES['userfile']['error']];

 
// do whatever with the error message

}
// In a loop...

for($x=0,$y=count($_FILES['userfile']['error']);$x<$y;++$x) {

  if(
$_FILES['userfile']['error'][$x]==0) {

   
// process

 
} else {

   
$error_message = $error_types[$_FILES['userfile']['error'][$x]];

   
// Do whatever with the error message

 
}

}
// When you're done... if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory

unset($error_types);

?>


jille at quis dot cx

13 years ago


UPLOAD_ERR_PARTIAL is given when the mime boundary is not found after the file data. A possibly cause for this is that the upload was cancelled by the user (pressed ESC, etc).

sysadmin at cs dot fit dot edu

17 years ago


I noticed that on PHP-4.3.2 that $_FILES can also not be set if the file uploaded exceeds the limits set by upload-max-filesize in the php.ini, rather than setting error $_FILES["file"]["error"]

tyler at fishmas dot org

18 years ago


In regards to the dud filename being sent, a very simple way to check for this is to check the file size as well as the file name.  For example, to check the file size simple use the size attribute in your file info array:

<?php

if($_FILES["file_id"]["size"]  == 0)

{

        
// ...PROCESS ERROR

}

?>


Tom

12 years ago


Note: something that might surprise you, PHP also provides a value in the $_FILES array, if the input element has no value at all, stating an error UPLOAD_ERR_NO_FILE.

So UPLOAD_ERR_NO_FILE is not an error, but a note that the input element just had no value. Thus you can't rely on the $_FILES array to see if a file was provided. Instead you have to walk the array and check every single damn entry - which can be quite difficult since the values may be nested if you use input elements named like "foo[bar][bla]".

Seems like PHP just introduced you to yet another common pitfall.


admin at compumatter dot com

3 years ago


We use this function to handle file uploads.

Since $_FILES allows for more than a single file, this loops through each file and if there's an error, it is displayed in human readable language to the error log and then returned / exited.  You can adjust that to echo's if preferred:

function file_upload_test($messageBefore="CM FILE UPLOAD MESSAGE"){
    global $_FILES;
    # a single file limit
    $upload_max_size = ini_get('upload_max_filesize');
    # the combination of a batch o multiple files
    $post_max_size = ini_get('post_max_size');
    # array of possible fails which are retuned below in if $key=error section
    $phpFileUploadErrors = array(
        0 => 'There is no error, the file uploaded with success',
        1 => 'Exceeds php.ini upload_max_filesize of '.$upload_max_size.'MB',
        2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
        3 => 'The uploaded file was only partially uploaded',
        4 => 'No file was uploaded',
        6 => 'Missing a temporary folder',
        7 => 'Failed to write file to disk.',
        8 => 'A PHP extension stopped the file upload.',
    );

    error_log("========================================");
    error_log("$messageBefore");
    error_log("========================================");
    foreach ($_FILES['cmmediabrowsedfor'] as $key => $value) {
       ${$key}=$value;
       error_log('$_FILES ['.$key.'] = ['.$value.']');
       if(is_array($value)){
            foreach ($value as $key2 => $value2) {
                error_log('   >   $_FILES ['.$key.']['.$key2.'] = '.$value2);
                if($key=='error'){
                     error_log('   ******* CM Failed Upload: '.$phpFileUploadErrors[$value2]);
                     error_log('           Exit / Return in plugins/cm-alpha/php/images/img-create-tmp.php');
                     error_log(' ');
                     exit;
                }
            }
       }
    }
    if(!file_exists($_FILES["cmmediabrowsedfor"]["tmp_name"][0]) || !is_uploaded_file($_FILES["cmmediabrowsedfor"]["tmp_name"][0])) {
        error_log("NO FILE GOT UPLOADED ");
    } else {
        error_log("SUCCESS FILE GOT UPLOADED ");
    }
}


rlerne at gmail dot com

8 years ago


This updates "adam at gotlinux dot us" above and makes it version aware, and also adds newer constants to the array.

The reason we want to check the version is that the constants are not defined in earlier versions, and they appear later in the array. They would effectively overwrite the "0" index (no error) with an error message when the file actually uploaded fine.

It also drops the constant's value (0,1,2, etc) for the errors, in the likely event that they are changed later (the code should still work fine).

<?php

$upload_errors

= array(
   
0                        => "There is no error, the file uploaded with success"
   
,UPLOAD_ERR_INI_SIZE    => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
   
,UPLOAD_ERR_FORM_SIZE    => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
   
,UPLOAD_ERR_PARTIAL        => "The uploaded file was only partially uploaded"
   
,UPLOAD_ERR_NO_FILE        => "No file was uploaded"
);

if (

version_compare(PHP_VERSION, '5.0.3') >= 0)
   
$upload_errors[UPLOAD_ERR_NO_TMP_DIR] = "Missing a temporary folder";

if (

version_compare(PHP_VERSION, '5.1.0') >= 0)
   
$upload_errors[UPLOAD_ERR_CANT_WRITE] = "Failed to write to disk";

if (

version_compare(PHP_VERSION, '5.2.0') >= 0)
   
$upload_errors[UPLOAD_ERR_EXTENSION] = "File upload stopped by extension";
?>


belowtherim2000 at yahoo dot com

15 years ago


I've been playing around with the file size limits and with respect to the post_max_size setting, there appears to be a hard limit of 2047M.  Any number that you specify above that results in a failed upload without any informative error describing what went wrong.  This happens regardless of how small the file you're uploading may be.  On error, my page attempts to output the name of the original file.  But what I discovered is that this original file name, which I maintained in a local variable, actually gets corrupted.  Even my attempt to output the error code in $_FILES['uploadedfiles']['error'] returns an empty string/value.

Hopefully, this tidbit will save someone else some grief.


viseth10 at gmail dot com

5 years ago


[Well just a little note. ]
That UploadException class example posted on top by anonymous is great. It works good. But there is a certain problem. You know there are two sides to generating errors.
First -> for the client side.
Second -> for the developers who will use your script

But i see only one side to generating Exceptions. ie For the developers.

Why ? Because when you generate an Exception, your script will come to an halt and do whatever you have defined in catch clause.
Now you dont want any client to see the Exception, do you ? I will not. The client will want to know what error occured in simple words they can understand instead of wanting their web app crashed if upload fails. So,  dont generate exceptions. These errors should be collected and shown to client in an elegant way. That's a little advice.
Keep developing smarter.


krissv at ifi.uio.no

18 years ago


When $_FILES etc is empty like Dub spencer says in the note at the top and the error is not set, that might be because the form enctype isnt sat correctly. then nothing more than maybe a http server error happens.

enctype="multipart/form-data" works fine


roger dot vermeir at nokia dot com

4 years ago


Just found out that it is very important to define the
input type="hidden" name="MAX_FILE_SIZE" value=...
AFTER defining the input type="FILE" name=...
in your html/php.
If you swap them around, you will keep getting the filesize exceeded (error 2)!
Hope this helps.
Roger

Dub Spencer

18 years ago


Upload doesnt work, and no error?

actually, both $_FILES and $_REQUEST in the posted to script are empty?

just see, if  "post_max_size" is lower than the data you want to load.

in the apache error log, there will be an entry like "Invalid method in request". and in the access log, there will be two requests: one for the POST, and another that starts with all "----" and produces a 501.


web att lapas dott id dott lv

15 years ago


1. And what about multiple file upload ? - If there is an UPLOAD_ERR_INI_SIZE error with multiple files - we can`t detect it normaly ? ...because that we have an array, but this error returns null and can`t use foreach. So, by having a multiple upload, we can`t normaly inform user about that.. we can just detect, that sizeof($_FILES["file"]["error"]) == 0 , but we can`t actualy return an error code. The max_file_size also is not an exit, becouse it refers on each file seperatly, but upload_max_filesize directive in php.ini refers to all files together. So, for example, if upload_max_filesize=8Mb , max_file_size = 7Mb and one of my files is 6.5Mb and other is 5Mb, it exeeds the upload_max_filesize - cant return an error, becouse we don`t know where to get that error.
Unfortunately we cannot get the file sizes on client side, even AJAX normaly can`t do that.

2. If in file field we paste something, like, D:whatever , then there also isn`t an error to return in spite of that no such file at all.


info at foto50 dot com

15 years ago


For those reading this manual in german (and/or probably some other languages) and you miss error numbers listed here, have a look to the english version of this page ;)

Tom

8 years ago


As it is common to use move_uploaded_file with file uploads, how to get it's error messages should be noted here (especially since it's not noted anywhere else in the manual).
Common code is to do something like:
if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file)) {
      echo "<P>FILE UPLOADED TO: $target_file</P>";
   } else {
      echo "<P>MOVE UPLOADED FILE FAILED!!</P>";
      print_r(error_get_last());
   }

<!DOCTYPE html>

<?php

    $target_dir = $_POST["directory_name"]."/";

    $target_file = $target_dir . basename($_FILES["file"]["name"]);

    $name = $_FILES["file"]["name"];

    $type = $_FILES["file"]["type"];

    $size = $_FILES["file"]["size"];

    $flag = 1;

    if($_SERVER["REQUEST_METHOD"] == "POST")

   {

        if(!empty($_POST["directory_name"]))

        {

            if(!is_dir($_POST["directory_name"])) {

                echo "Creating Directory ..!!";

                mkdir($_POST["directory_name"]);    

                $flag = 1;            

            }

        }

       else

       {

          echo "<b>Error: Specify the directory name...</b>";

          $flag = 0;

          exit;    

       }    

    if(isset($_FILES["file"]) && $_FILES["file"]["error"] == 0)

    {

        $allowed_ext = array("jpg" => "image/jpg",

                            "jpeg" => "image/jpeg",

                            "png" => "image/png");

        $ext = pathinfo($name, PATHINFO_EXTENSION);

        if (!array_key_exists($ext, $allowed_ext))    

        {

            die("<b>Error: Please select a valid file format.</b>");

        }    

        $maxsize = 200000;

        if ($size > $maxsize)    

        {

            die("<b>Error: ". $_FILES["file"]["error"] . 

            "  File size is larger than the allowed limit.</b>");

        }    

        if (in_array($type, $allowed_ext))

        {

            if (file_exists("$target_dir/".$_FILES["file"]["name"]))    

            {

                echo "<b>".$_FILES["file"]["name"]." is already exists.</b>";

            }        

            else

            {

                if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {

                    echo "<b>The "$_FILES["file"]["name"]. " has been uploaded.</b>";

                

                else 

                {

                    echo "<b>Error : ". $_FILES["file"]["error"] .

                    " Sorry, there was an error uploading your file.";

                }

            }

        }

        else

        {

            echo "<b>Error: ". $_FILES["file"]["error"] . " Please try again.</b>";

        }

    }

    else

    {

        echo "<b>Error: ". $_FILES["file"]["error"] . " File is not uploaded</b>";

    }

  }

?>

</body>

</html>

За последние 24 часа нас посетили 11595 программистов и 1180 роботов. Сейчас ищут 266 программистов …


  1. fenixlz

    fenixlz
    Активный пользователь

    С нами с:
    23 ноя 2011
    Сообщения:
    5
    Симпатии:
    0
    Адрес:
    Красноярск

    Всем привет! На сайте нужна загрузка файлов. Ну обшарил интернет, нашел как сделать, но не работает. is_uploaded_file($_FILES[«filename»][«tmp_name»] по всей видимости, возвращает FALSE и файла на сервере не появляется. Все перепробовал, ничего не могу сделать :( Может хоть вы поможете.

    Форма:

    1.       <form action=«upload.php» method=«post» enctype=«multipart/form-data»>
    2.       <input type=«hidden» name=«MAX_FILE_SIZE» value=«30000»>
    3.       <input type=«file» name=«filename»><br>
    4.       <input type=«submit» value=«Загрузить»><br>

    Скрипт обработки upload.php:

    1.    if($_FILES[«filename»][«size»] > 1024*3*1024)
    2.      echo («Размер файла превышает три мегабайта»);
    3.    // Проверяем загружен ли файл
    4.      // Если файл загружен успешно, перемещаем его
    5.      // из временной директории в конечную
    6.      move_uploaded_file($_FILES[«filename»][«tmp_name»], «/home/p*****/www/sitename.url.ru/uploads/».$_FILES[«filename»][«name»]);
    7.       echo(«Ошибка загрузки файла»);


  2. Gromo

    Gromo
    Активный пользователь

    С нами с:
    24 май 2010
    Сообщения:
    2.786
    Симпатии:
    2
    Адрес:
    Ташкент


  3. fenixlz

    fenixlz
    Активный пользователь

    С нами с:
    23 ноя 2011
    Сообщения:
    5
    Симпатии:
    0
    Адрес:
    Красноярск

    Взял готовые решения по этой ссылке, форму и скрипт. Все равно ничего не работает. Вывело:

    1. Возможная атака с помощью файловой загрузки!
    2. Некоторая отладочная информация:Array

    В чем косяк то?


  4. fenixlz

    fenixlz
    Активный пользователь

    С нами с:
    23 ноя 2011
    Сообщения:
    5
    Симпатии:
    0
    Адрес:
    Красноярск

    В чем разница

    <input type=»file» name=»filename«>
    и
    <input type=»file» name=»userfile«> ? Только в имени?


  5. Gromo

    Gromo
    Активный пользователь

    С нами с:
    24 май 2010
    Сообщения:
    2.786
    Симпатии:
    2
    Адрес:
    Ташкент

    fenixlz
    да, только в имени. раз у тебя не получается, значит что-то упускаешь. возможно права на запись в папку назначения :)

    вот то, что использую я в своём скрипте для загрузки файлов

    1.       if(isset($_FILES[‘file’]) && $_FILES[‘file’][‘error’] == UPLOAD_ERR_OK){


  6. fenixlz

    fenixlz
    Активный пользователь

    С нами с:
    23 ноя 2011
    Сообщения:
    5
    Симпатии:
    0
    Адрес:
    Красноярск

    Gromo до записи в папку назначения дело даже не доходит.

    является FALSE и поэтому писать в папку даже не пытается, а выводит сообщение об ошибке.


  7. Mamont

    Mamont
    Активный пользователь

    С нами с:
    5 дек 2010
    Сообщения:
    183
    Симпатии:
    0

PHP File Upload Error Codes

// UPLOAD_ERR_OK         Value: 0
// There is no error, the file uploaded with success.

// UPLOAD_ERR_INI_SIZE Value: 1
// The uploaded file exceeds the upload_max_filesize directive in php.ini.

// UPLOAD_ERR_FORM_SIZE Value: 2
// The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

// UPLOAD_ERR_PARTIAL    Value: 3
// The uploaded file was only partially uploaded.

// UPLOAD_ERR_NO_FILE    Value: 4
// No file was uploaded.

// UPLOAD_ERR_NO_TMP_DIR Value: 6
// Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.

// UPLOAD_ERR_CANT_WRITE Value: 7
// Failed to write file to disk. Introduced in PHP 5.1.0.

// UPLOAD_ERR_EXTENSION Value: 8
// A PHP extension stopped the file upload. Introduced in PHP 5.2.0.

<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name     = $_FILES['myfile']['name'];
    $type     = $_FILES['myfile']['type'];
    $tmp_name = $_FILES['myfile']['tmp_name'];
    $error    = $_FILES['myfile']['error'];
    $size     = $_FILES['myfile']['size'];

    switch ($error) {
        case UPLOAD_ERR_OK:
            $response = 'There is no error, the file uploaded with success.';
            break;
        case UPLOAD_ERR_INI_SIZE:
            $response = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
            break;
        case UPLOAD_ERR_FORM_SIZE:
            $response = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
            break;
        case UPLOAD_ERR_PARTIAL:
            $response = 'The uploaded file was only partially uploaded.';
            break;
        case UPLOAD_ERR_NO_FILE:
            $response = 'No file was uploaded.';
            break;
        case UPLOAD_ERR_NO_TMP_DIR:
            $response = 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.';
            break;
        case UPLOAD_ERR_CANT_WRITE:
            $response = 'Failed to write file to disk. Introduced in PHP 5.1.0.';
            break;
        case UPLOAD_ERR_EXTENSION:
            $response = 'File upload stopped by extension. Introduced in PHP 5.2.0.';
            break;
        default:
            $response = 'Unknown upload error';
            break;
    }

    echo $response;
} else {
    echo
        '<form action="upload.php" enctype="multipart/form-data" method="post">' .
            '<input name="myfile" type="file" /><br />' .
            '<input type="submit" value="Submit" />' .
        '</form>' .
        '';
}

Добрый день!

При загрузке медиафайлов появляется ошибка HTTP. Как ее исправить?

Ошибка HTTP

Ответ

Эта ошибка обычно возникает, когда Вы загружаете изображение или другие файлы в WordPress с помощью встроенного загрузчика мультимедиа.

Есть несколько причин, которые могут привести к ошибке HTTP при попытке загрузить файлы с помощью медиазагрузчика WordPress. В принципе, WordPress не может понять причину, и поэтому он отображает общее сообщение об ошибке.

Для решения задачи существует несколько способов. Рассмотрим их более подробно.

Способ 1. Убедитесь, что ошибка HTTP не временная

Во-первых, Вы должны подождать несколько минут, а затем повторить попытку загрузить файл изображения. Эта ошибка иногда бывает вызвана необычным трафиком и низкими ресурсами сервера, которые автоматически фиксируются на большинстве серверов хостинга WordPress. Если это не сработает, попробуйте загрузить другой файл изображения. Если другой файл загружен успешно, попробуйте сохранить исходный файл изображения меньшего размера и повторите загрузку.

Наконец, Вы можете попробовать сохранить файл в другом формате. Например, смените jpeg на png с помощью программного обеспечения для редактирования изображений. После этого повторите загрузку файла.

Если все эти шаги все равно приводят к ошибке, это означает, что ошибка не вызвана временным сбоем и определенно требует вашего непосредственного внимания.

Способ 2. Увеличьте предел памяти WordPress

Наиболее распространенной причиной этой ошибки является нехватка памяти для использования WordPress. Чтобы исправить это, Вам нужно увеличить объем памяти, который PHP может использовать сервере. Это можно сделать, добавив следующий код в основной конфигурационный файл wp-config.php:

define ('WP_MEMORY_LIMIT', '256M');

Этот код увеличивает предел памяти WordPress до 256 МБ, чего будет достаточно для устранения проблем с ограничениями памяти.

Способ 3. Измените библиотеку редактора изображений, используемую WordPress

WordPress работает на PHP, который использует два модуля для обработки изображений. Эти модули называются GD Library и Imagick. “Движок” может использовать любой из них, в зависимости от того, какой из них доступен.

Тем не менее, Imagick, как известно, часто сталкивается с проблемами памяти, вызывающими ошибку HTTP во время загрузки изображений. Чтобы исправить это, Вы можете сделать библиотеку GD редактором изображений по умолчанию.

Для этого необходимо добавить этот код в файл functions.php Вашей темы:

function wpschool_image_editor_default_to_gd( $editors ) {
    $gd_editor = 'WP_Image_Editor_GD';
    $editors = array_diff( $editors, array( $gd_editor ) );
    array_unshift( $editors, $gd_editor );
    return $editors;
}
add_filter( 'wp_image_editors', 'wpschool_image_editor_default_to_gd' );

Если Вы не знаете, как редактировать functions.php, то в этом случае Вам поможет плагин ProFunctions.

После добавления кода Вы можете повторить загрузку файлов с помощью загрузчика мультимедиа. Если это не решит проблему, можете удалить этот код и попробовать другие методы, описанные в этом материале.

Способ 4. Использование метода .htaccess

Этот метод позволяет Вам контролировать, как Imagick использует серверные ресурсы. Многие хостинг-провайдеры ограничивают способность Imagick использовать несколько потоков для более быстрой обработки изображений. Однако это приведет к появлению ошибки HTTP при загрузке изображений. Простой способ исправить это – добавить следующий код в файл .htaccess, который находится в корневом каталоге сайта:

SetEnv MAGICK_THREAD_LIMIT 1

Этот код просто ограничивает модель Imagick одним потоком для обработки изображений.

Также читайте: 504 тайм аут шлюза – что это, методы решения.

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

  • Remove From My Forums
  • Question

  • Hi.

    I am trying to upload multiple documents to a sub folder in a library using powershell.

    I am getting the error as : ForEach-Object : Exception calling «Add» with «3» argument(s):
    «<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file
    with URL ‘server/TestLibrary/User_image/ab_3f_wht_ist_small_gif.gif’ in this Web.»

    I have used the below code:

    function UploadImages($weburl)
    {
    $docLibraryName = "TestLibrary"
    $localFolderPath = "C:UsersImgsuser_image" 
    
    Add-PsSnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue 
    $web = Get-SPWeb -Identity $webUrl
    
    $docLibrary = $web.Lists[$docLibraryName] 
    $subFolderName="user_image" 
    
    Add-PsSnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue 
    $web = Get-SPWeb -Identity $webUrl
    
    $docLibrary = $web.Lists[$docLibraryName] 
    
    #Attach to local folder and enumerate through all files
    
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles() | ForEach-Object { 
    
        #Create file stream object from file
        $fileStream = ([System.IO.FileInfo] (Get-Item $_.FullName)).OpenRead()
        $contents = new-object byte[] $fileStream.Length
        $fileStream.Read($contents, 0, [int]$fileStream.Length);
        $fileStream.Close(); 
    
        write-host "Copying" $_.Name "to" $docLibrary.Title "in" $web.Title "..." 
    
        #Add file
        $folder = $web.getfolder($docLibrary.Title + "/" + $subFolderName) 
        write-host "folder is " $folder
        $spFile = $folder.Files.Add($folder.Url + "/" + $_.Name, $contents, $true)
    
        $spItem = $spFile.Item 
    
    Write-Host -f Green "Added Images to Library !!!"
    }
    $web.Dispose() 
    }

    How to fix this?

    Thanks

    • Edited by

      Monday, July 7, 2014 12:34 PM

Answers

  • Found the solution, by changing to below line:

     $folder = $web.getfolder($docLibrary.rootFolder.URL
    + «/» + $subFolderName)

    • Marked as answer by
      Venkatzeus
      Thursday, July 10, 2014 2:07 PM

Понравилась статья? Поделить с друзьями:
  • Upload failed please try again later geometry dash как исправить
  • Upload error тильда
  • Upload error саундклауд
  • Upload error tilda
  • Upload error please try again later перевод