Answers.Body: <p>Cant you just do as described in the craft docs?  -> <a href="https://craftcms.com/docs/assets-fields#uploading-files-from-front-end-entry-forms" rel="nofollow noreferrer">https://craftcms.com/docs/assets-fields#uploading-files-from-front-end-entry-forms</a></p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-25T15:51:53.630Z
Answers.Text: I am using the same form, but i am using a custom controller that throws the error.
Answers.UserDisplayName: HendrikEng
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-25T13:05:03.983Z
Answers.LastActivityDate: 2018-03-25T13:05:03.983Z
Answers.UserDisplayName: Gįëł Tėttëłæår
Answers.Body: <p>use $allowAnonymous feature in your controller to allow your function to work if you are not logged in when uploading[just assuming you are trying to upload this as logged off user.]</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-25T23:01:20.860Z
Answers.Text: thanks for the answer, its a cp-tab and only used when someone is logged in into the backend, i must have made a mistake somewhere else
Answers.UserDisplayName: HendrikEng
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-25T22:55:49.007Z
Answers.LastActivityDate: 2018-03-25T22:55:49.007Z
Answers.UserDisplayName: sailendra mangranti
Body: <p>I have been looking through answers here at stackexchange but somehow can't figure out what i am missing. I simply want to upload an asset to a specific asset folder in my plugin.</p>
  
  <p><s>I do get an error: <code>Call to a member function getTempName() on null</code></s></p>
  
  <p>Thanks a lot, much appreciated
  <s>
  this is my form:</p>
  
  <pre><code>&lt;form method="POST" enctype="multipart/form-data"&gt;
      &lt;input type="hidden" name="action" value="assetLinks/upload/UploadFile"&gt;
      {{ getCsrfInput() }}
    &lt;input type="file" name="file[]"&gt;
    &lt;button type="submit"&gt;Upload file&lt;/button&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>this is my controller:</p>
  
  <pre><code>&lt;?php
  namespace Craft;
  
  class AssetLinks_UploadController extends BaseController
  {
  
      public function actionUploadFile()
      {
          // Get info about the uploaded file
          $file = UploadedFile::getInstanceByName('fileInputName');
          $tempFilePath = $file-&gt;getTempName();
  
          // Find the target folder
          $folder = craft()-&gt;assets-&gt;findFolder(array(
              'sourceId' =&gt; 1,
              'path' =&gt; 'uploads/documents/',
          ));
  
          // Turn the file into a managed asset within that folder
          craft()-&gt;assets-&gt;insertFileByLocalPath(
              $file-&gt;getTempName(),
              $file-&gt;getName(),
              $folder-&gt;id,
              AssetConflictResolution::KeepBoth
          );
      }
  }
  </code></pre>
  
  <p></s></p>
  
  <p><strong>Update:</strong></p>
  
  <p>I have been reading through the docs and some other examples and decided to go for an AJAX File upload, which of course lead to new problems :-)</p>
  
  <p>this is the controller:</p>
  
  <pre><code>    &lt;?php
  namespace Craft;
  
  class AssetLinks_UploadController extends BaseController
  {
  
    protected $valid_extensions = array('jpg', 'jpeg', 'png', 'pdf');
    protected $assetSourceId = 1;
    public function actionUploadFile()
    {
        $this-&gt;requireAjaxRequest();
        $errors = array();
        $success = array();
        foreach ($_FILES['files']['error'] as $key =&gt; $error)
        {
            if (!$error)
            {
                $filename = $_FILES['file']['name'][$key];
                $file = $_FILES['file']['tmp_name'][$key];
                $filenamePieces = explode('.', $filename);
                $extension = end($filenamePieces);
                if (!in_array($extension, $this-&gt;valid_extensions))
                {
                    $errors[] = "$filename has an invalid extension.";
                    continue;
                }
  
                $uploadDir = craft()-&gt;assetSources-&gt;getSourceById($this-&gt;uploadAssetSourceId)-&gt;settings['path'];
                $uploadDir = str_replace('{basePath}', craft()-&gt;config-&gt;get('environmentVariables')['basePath'], $uploadDir);
                if (move_uploaded_file($file, $uploadDir . $filename))
                {
                    IOHelper::deleteFile($file);
                    $file = $uploadDir . $filename;
                    $fileModel = new AssetFileModel();
                    $fileModel-&gt;sourceId = $this-&gt;assetSourceId;
                    $fileModel-&gt;folderId = $this-&gt;assetFolderId;
                    $fileModel-&gt;filename = IOHelper::getFileName($filename);
                    $fileModel-&gt;kind = IOHelper::getFileKind(IOHelper::getExtension($filename));
                    $fileModel-&gt;size = filesize($file);
                    $fileModel-&gt;dateModified = IOHelper::getLastTimeModified($file);
                    craft()-&gt;assets-&gt;storeFile($fileModel);
                    $success[] = "$filename was saved.";
                }
                else
                {
                    $errors[] = "$filename was unable to be saved.";
                    continue;
                }
            }
        }
        $this-&gt;returnJSON(compact('errors', 'success'));
    }
  }
  </code></pre>
  
  <p>and this is the form and Ajax post:</p>
  
  <pre><code>{% extends "_layouts/cp" %}
  {% set title = 'Asset Links' %}
  
  {% set content %}
  
  
    &lt;form class="upload"  method="POST" enctype="multipart/form-data"&gt;
      &lt;input  type="hidden" name="action" value="assetLinks/upload/UploadFile"&gt;
      {{ getCsrfInput() }}
      &lt;input class="file btn" type="file" name="file"&gt;
      &lt;button data-icon="upload" class="uploadfile btn submit" type="submit"&gt;Upload file&lt;/button&gt;
    &lt;/form&gt;
    &lt;div style="margin-top:20px" id="output" /&gt;
  
  
  {% endset %}
  
  
  {% set js %}
      $(function() {
        $("form").submit(function() {
          var url = '/actions/assetLinks/upload',
            files = $(this).find("[name=file]")[0].files,
            formdata = new FormData(),
            file,
            reader;
  
          for (var i = 0; i &lt; files.length; i++) {
            file = files[i];
            if (window.FileReader) {
              reader = new FileReader();
              reader.readAsDataURL(file);
            }
            formdata.append("files[]", file);
          }
  
          $("#output").html("Uploading...");
  
        $.ajax({
          type: "POST",
          url: url,
          data: formdata,
          processData: false,
            contentType: false,
          success: function(json) {
            window.json = json;
            console.log(json);
  
            var errors = json['errors'],
                success = json['success'],
                html = "&lt;p&gt;&lt;b&gt;" + errors.length + " errors, " + success.length + " successfully uploaded&lt;/b&gt;&lt;/p&gt;";
  
                $("#output").html(html);
          },
          error: function (xhr, ajaxOptions, thrownError) {
            alert("ERROR: " + xhr.status + " " + thrownError);
          }
        });
  
          return false;
        });
      })
  {% endset %}
  {% includeJs js %}
  </code></pre>
  
  <p>in wich i run into a 404, 
  <code>http://test.test/actions/assetLinks/upload 404 (Not Found)</code></p>
  
  <p>it seems like i am addressing the wrong controller url ?</p>
  
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2018-03-25T16:07:32.070Z
Comments.Text: Are you using the correct field name for $file = UploadedFile::getInstanceByName('fileInputName')?
Comments.UserDisplayName: Andris Sevcenko
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2018-03-25T16:14:09.667Z
Comments.Text: I am not sure to be honest, i posted all the data that is used in the plugin so its basically just the form and the uploadController
Comments.UserDisplayName: HendrikEng
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2018-03-25T21:01:17.353Z
Comments.Text: @AndrisSevcenko you were right was blind, i changed the input name to:file and  $file = UploadedFile::getInstanceByName('file');. it doesn't throw an error but doesn't upload anything
Comments.UserDisplayName: HendrikEng
Tags: <plugin-development><templating><assets><assetfilemodel>
Title: Uploading an Asset from a custom CP-Tab in Craft 2.x
ThreadText: # Uploading an Asset from a custom CP-Tab in Craft 2.x
  
  (Asked by: username_0 on 2018-03-24)
  
  I have been looking through answers here at stackexchange but somehow can't figure out what i am missing. I simply want to upload an asset to a specific asset folder in my plugin.
  
  ~~I do get an error: `Call to a member function getTempName() on null`~~
  
  Thanks a lot, much appreciated
  ~~this is my form:~~
  
  ```
  <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="action" value="assetLinks/upload/UploadFile">
      {{ getCsrfInput() }}
    <input type="file" name="file[]">
    <button type="submit">Upload file</button>
  </form>
  
  ```
  
  this is my controller:
  
  ```
  <?php
  namespace Craft;
  
  class AssetLinks_UploadController extends BaseController
  {
  
      public function actionUploadFile()
      {
          // Get info about the uploaded file
          $file = UploadedFile::getInstanceByName('fileInputName');
          $tempFilePath = $file->getTempName();
  
          // Find the target folder
          $folder = craft()->assets->findFolder(array(
              'sourceId' => 1,
              'path' => 'uploads/documents/',
          ));
  
          // Turn the file into a managed asset within that folder
          craft()->assets->insertFileByLocalPath(
              $file->getTempName(),
              $file->getName(),
              $folder->id,
              AssetConflictResolution::KeepBoth
          );
      }
  }
  
  ```
  
  **Update:**
  
  I have been reading through the docs and some other examples and decided to go for an AJAX File upload, which of course lead to new problems :-)
  
  this is the controller:
  
  ```
      <?php
  namespace Craft;
  
  class AssetLinks_UploadController extends BaseController
  {
  
    protected $valid_extensions = array('jpg', 'jpeg', 'png', 'pdf');
    protected $assetSourceId = 1;
    public function actionUploadFile()
    {
        $this->requireAjaxRequest();
        $errors = array();
        $success = array();
        foreach ($_FILES['files']['error'] as $key => $error)
        {
            if (!$error)
            {
                $filename = $_FILES['file']['name'][$key];
                $file = $_FILES['file']['tmp_name'][$key];
                $filenamePieces = explode('.', $filename);
                $extension = end($filenamePieces);
                if (!in_array($extension, $this->valid_extensions))
                {
                    $errors[] = "$filename has an invalid extension.";
                    continue;
                }
  
                $uploadDir = craft()->assetSources->getSourceById($this->uploadAssetSourceId)->settings['path'];
                $uploadDir = str_replace('{basePath}', craft()->config->get('environmentVariables')['basePath'], $uploadDir);
                if (move_uploaded_file($file, $uploadDir . $filename))
                {
                    IOHelper::deleteFile($file);
                    $file = $uploadDir . $filename;
                    $fileModel = new AssetFileModel();
                    $fileModel->sourceId = $this->assetSourceId;
                    $fileModel->folderId = $this->assetFolderId;
                    $fileModel->filename = IOHelper::getFileName($filename);
                    $fileModel->kind = IOHelper::getFileKind(IOHelper::getExtension($filename));
                    $fileModel->size = filesize($file);
                    $fileModel->dateModified = IOHelper::getLastTimeModified($file);
                    craft()->assets->storeFile($fileModel);
                    $success[] = "$filename was saved.";
                }
                else
                {
                    $errors[] = "$filename was unable to be saved.";
                    continue;
                }
            }
        }
        $this->returnJSON(compact('errors', 'success'));
    }
  }
  
  ```
  
  and this is the form and Ajax post:
  
  ```
  {% extends "_layouts/cp" %}
  {% set title = 'Asset Links' %}
  
  {% set content %}
  
    <form class="upload"  method="POST" enctype="multipart/form-data">
      <input  type="hidden" name="action" value="assetLinks/upload/UploadFile">
      {{ getCsrfInput() }}
      <input class="file btn" type="file" name="file">
      <button data-icon="upload" class="uploadfile btn submit" type="submit">Upload file</button>
    </form>
    <div style="margin-top:20px" id="output" />
  
  {% endset %}
  
  {% set js %}
      $(function() {
        $("form").submit(function() {
          var url = '/actions/assetLinks/upload',
            files = $(this).find("[name=file]")[0].files,
            formdata = new FormData(),
            file,
            reader;
  
          for (var i = 0; i < files.length; i++) {
            file = files[i];
            if (window.FileReader) {
              reader = new FileReader();
              reader.readAsDataURL(file);
            }
            formdata.append("files[]", file);
          }
  
          $("#output").html("Uploading...");
  
        $.ajax({
          type: "POST",
          url: url,
          data: formdata,
          processData: false,
            contentType: false,
          success: function(json) {
            window.json = json;
            console.log(json);
  
            var errors = json['errors'],
                success = json['success'],
                html = "<p><b>" + errors.length + " errors, " + success.length + " successfully uploaded</b></p>";
  
                $("#output").html(html);
          },
          error: function (xhr, ajaxOptions, thrownError) {
            alert("ERROR: " + xhr.status + " " + thrownError);
          }
        });
  
          return false;
        });
      })
  {% endset %}
  {% includeJs js %}
  
  ```
  
  in wich i run into a 404,
  `http://test.test/actions/assetLinks/upload 404 (Not Found)`
  
  it seems like i am addressing the wrong controller url ?
  
  **Tags:** plugin-development, templating, assets, assetfilemodel
  
  > **Comments:**
  > **username_1**: Are you using the correct field name for $file = UploadedFile::getInstanceByName('fileInputName')?  
  > **username_0**: I am not sure to be honest, i posted all the data that is used in the plugin so its basically just the form and the uploadController  
  > **username_0**: @username_1 you were right was blind, i changed the input name to:file and  $file = UploadedFile::getInstanceByName('file');. it doesn't throw an error but doesn't upload anything  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_2 on 2018-03-25. Score: 1
  
  Cant you just do as described in the craft docs? -> <https://craftcms.com/docs/assets-fields#uploading-files-from-front-end-entry-forms>
  
  > **Comments:**
  > **username_0**: I am using the same form, but i am using a custom controller that throws the error.  
  
  ---
  
  ### Answer by username_3 on 2018-03-25. Score: 0
  
  use $allowAnonymous feature in your controller to allow your function to work if you are not logged in when uploading[just assuming you are trying to upload this as logged off user.]
  
  > **Comments:**
  > **username_0**: thanks for the answer, its a cp-tab and only used when someone is logged in into the backend, i must have made a mistake somewhere else  
  
  ---
  
  