Uploading single file using <input type="file">

Adshi

Member
I trying to upload images without using built-in attachment system. I using XenForo_Upload::getUploadedFile($field) to get uploaded file but it's always return false. Any ideas what I am doing wrong?

@EDIT
I have enctype="multipart/form-data" in form.
 

Chris D

XenForo developer
Staff member
Something like this will work:

HTML:
<input type="file" name="upload_file" id="ctrl_upload_file" />
PHP:
$fileTransfer = new Zend_File_Transfer_Adapter_Http();
if ($fileTransfer->isUploaded('upload_file'))
{
	$fileInfo = $fileTransfer->getFileInfo('upload_file'); // upload_file is the name attribute from the input element
	$fileName = $fileInfo['upload_file']['tmp_name']; // $fileName is a string containing the path to the file uploaded in the temp location
}
 

rainfall

New member
i need help on this as well....

I add "enctype="multipart/form-data" this on my form tag already.
and i have declared $fileupload = XenForo_Upload::getUploadedFile('file_upload');
now what???

is there any genius out there who can solve this. been around for many days.... still no hope.
 

Chris D

XenForo developer
Staff member
Would need to see all of the code related to the form, the input and the PHP to be sure, really.
 

rainfall

New member
Would need to see all of the code related to the form, the input and the PHP to be sure, really.
Screenshot something like this


added a thread_classified template (basically it is Thread_add template width modified/added stuff)
added an upload_photo template
Then added a new function in forum.php

thread_classified
PHP:
<xen:title>{xen:phrase create_classified}</xen:title>

<xen:if is="{$forum.description} AND @threadListDescriptions">
    <xen:description class="baseHtml">{xen:raw $forum.description}</xen:description>
</xen:if>

<xen:navigation>
    <xen:breadcrumb source="$nodeBreadCrumbs" />
</xen:navigation>

<xen:container var="$head.robots">
    <meta name="robots" content="noindex" /></xen:container>
<xen:container var="$bodyClasses">{xen:helper nodeClasses, $nodeBreadCrumbs, $forum}</xen:container>
<xen:container var="$searchBar.forum"><xen:include template="search_bar_forum_only" /></xen:container>
  
<xen:container var="$head.pollCss"><style>.hasJs .PollNonJsInput { display: none }</style></xen:container>

<form enctype="multipart/form-data" action="{xen:link 'forums/add-classified', $forum}" method="post"
    class="xenForm Preview AutoValidator"
    data-previewUrl="{xen:link 'forums/create-thread/preview', $forum}"
    data-redirect="on">
    <xen:hook name="thread_classified">

    <xen:if is="{$visitor.user_id} == 0">
        <dl class="ctrlUnit">
            <dt><label for="ctrl_guestUsername">{xen:phrase name}:</label></dt>
            <dd><input type="text" name="_guestUsername" value="{$visitor.username}" class="textCtrl" /></dd>
        </dl>
  
        <!-- slot: after_guest -->
    </xen:if>

    <xen:include template="helper_captcha_unit" />

    <fieldset>
        <xen:include template="title_prefix_edit">
            <xen:set var="$selectedPrefix">{$prefixId}</xen:set>
            <xen:set var="$idSuffix">thread_create</xen:set>
        </xen:include>
  
        <dl class="ctrlUnit fullWidth surplusLabel">
            <dt><label for="ctrl_title_thread_create">{xen:phrase title}:</label></dt>
            <dd><input type="text" name="title" class="textCtrl titleCtrl" id="ctrl_title_thread_create" maxlength="100" autofocus="true"
                placeholder="{xen:phrase thread_title}..." value="{$title}"
                data-liveTitleTemplate="{xen:phrase create_thread}: <em>%s</em>" /></dd>
        </dl>

        <!--xen:hook name="thread_create_fields_main" params="{xen:array 'forum={$forum}'}" />
            <dl class="ctrlUnit fullWidth">
            <dt></dt>
            <dd>{xen:raw $editorTemplate}</dd>
        </dl-->
    </fieldset>

        <!-- rain added -->
      
        <dl class="ctrlUnit fullWidth surplusLabel"><center>
<table cellpadding=0 cellspacing=0 width=90% class=fullWidth>
<tr><td valign=top>
<div style="float:left;">
<xen:include template="upload_photo" />
</div>
<div style="float:left;">
<table cellpadding=0 cellspacing=0 width=100% style="padding-left:2px;">
  <col width=75><col>
  <tr><td>Name  
      <td><input type=text class=textCtrl id=model_name name=model_name>  
</table>
</div>
<tr><td>
<div><span style="font-size:14px;font-weight:bold;">About Me</span>
<textarea style="width:100%;height:150px;" name=about></textarea>
</div>
</table>      
        </center>
        </dl>
      
        <!-- end rain added -->
    </fieldset>
  
    <!-- slot: after_editor -->

    <dl class="ctrlUnit submitUnit">
        <dt></dt>
        <dd>
            <input disabled id=CTHD type="submit" value="{xen:phrase create_classified}" accesskey="s" class="button primary" />
        </dd>
    </dl>

    <xen:if is="{$attachmentParams}">
        <dl class="ctrlUnit AttachedFilesUnit">
            <dt><label for="ctrl_uploader">{xen:phrase attached_files}:</label></dt>
            <dd><xen:include template="attachment_editor">
                <xen:set var="$attachments" value="{$attachmentParams.attachments}" />
            </xen:include></dd>
        </dl>
      
        <!-- slot: after_attachment -->
    </xen:if>
  
    <xen:if is="{$visitor.user_id}">
        <fieldset>
            <dl class="ctrlUnit">
                <dt>{xen:phrase options}:</dt>
                <dd><ul>
                    <li><xen:include template="helper_thread_watch_input" /></li>
                </ul></dd>
            </dl>
  
            <xen:include template="thread_fields_status" />
        </fieldset>
      
        <!-- slot: after_options -->
    </xen:if>

    <xen:hook name="thread_create_fields_extra" params="{xen:array 'forum={$forum}'}" />  
  
    </xen:hook>


    <input type="hidden" name="_xfToken" value="{$visitor.csrf_token_page}" />
</form>

<xen:comment><xen:include template="editor" /></xen:comment>

upload_photo
PHP:
<script>
  function uploadPhoto(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
    document.getElementById('CTHD').disabled = true;
    continue;
      }else{
    document.getElementById('CTHD').disabled = false;
      }


      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          //document.getElementById('list').insertBefore(span, null);
          document.getElementById('list').innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }
</script>

<input type=file id=UPL name=UPL onchange="uploadPhoto(event);" />
<div style="width:226px;height:301px;border:1px solid black;text-align:center;vertical-align:middle;" id=list>
<br><br><br><br><br><br>Only images allowed.<br> You will not be able to create post if you try to upload other than images.
</div>
 
Last edited:

rainfall

New member
PHP:
    public function actionAddClassified()
    {
        $this->_assertPostOnly();

        $forumId = $this->_input->filterSingle('node_id', XenForo_Input::UINT);
        $forumName = $this->_input->filterSingle('node_name', XenForo_Input::STRING);

        $ftpHelper = $this->getHelper('ForumThreadPost');
        $forum = $ftpHelper->assertForumValidAndViewable($forumId ? $forumId : $forumName);

        $forumId = $forum['node_id'];

        $this->_assertCanPostThreadInForum($forum);

        if (!XenForo_Captcha_Abstract::validateDefault($this->_input))
        {
            return $this->responseCaptchaFailed();
        }

        $visitor = XenForo_Visitor::getInstance();

        $input = $this->_input->filter(array(
            'title' => XenForo_Input::STRING,
            'prefix_id' => XenForo_Input::UINT,
            'attachment_hash' => XenForo_Input::STRING,

            'watch_thread_state' => XenForo_Input::UINT,
            'watch_thread' => XenForo_Input::UINT,
            'watch_thread_email' => XenForo_Input::UINT,

            '_set' => array(XenForo_Input::UINT, 'array' => true),
            'discussion_open' => XenForo_Input::UINT,
            'sticky' => XenForo_Input::UINT,

            'poll' => XenForo_Input::ARRAY_SIMPLE, // filtered below
        ));
     
        $upload = XenForo_Upload::getUploadedFile('UPL');

        $input['message'] = "[TABLE]";
        $input['message'] .= "[TR][TDROWSPAN=2][IMG]http://192.168.1.40/xx/data/escort/download.jpg[/IMG][/TDROWSPAN]";
        $input['message'] .= "[TD]Name[/TD][TD]" . $this->_input->filterSingle('model_name', XenForo_Input::STRING) . "[/TD][/TR]";
        $input['message'] .= "[TR][TDCOLSPAN=2][H2]About Me[/H2]".  $this->_input->filterSingle('about', XenForo_Input::STRING) ."[/TDCOLSPAN]";
        $input['message'] .= "[/TABLE]";
        $input['message'] = XenForo_Helper_String::autoLinkBbCode($input['message']);


        if (!$this->_getPrefixModel()->verifyPrefixIsUsable($input['prefix_id'], $forumId))
        {
            $input['prefix_id'] = 0; // not usable, just blank it out
        }

        $pollInputHandler = new XenForo_Input($input['poll']);
        $pollInput = $pollInputHandler->filter(array(
            'question' => XenForo_Input::STRING,
            'responses' => array(XenForo_Input::STRING, 'array' => true),
            'multiple' => XenForo_Input::UINT,
            'public_votes' => XenForo_Input::UINT,
            'close' => XenForo_Input::UINT,
            'close_length' => XenForo_Input::UNUM,
            'close_units' => XenForo_Input::STRING
        ));

        // note: assumes that the message dw will pick up the username issues
        $writer = XenForo_DataWriter::create('XenForo_DataWriter_Discussion_Thread');
        $writer->bulkSet(array(
            'user_id' => $visitor['user_id'],
            'username' => $visitor['username'],
            'title' => $input['title'],
            'prefix_id' => $input['prefix_id'],
            'node_id' => $forumId
        ));

        // discussion state changes instead of first message state
        $writer->set('discussion_state', $this->getModelFromCache('XenForo_Model_Post')->getPostInsertMessageState(array(), $forum));

        // discussion open state - moderator permission required
        if (!empty($input['_set']['discussion_open']) && $this->_getForumModel()->canLockUnlockThreadInForum($forum))
        {
            $writer->set('discussion_open', $input['discussion_open']);
        }

        // discussion sticky state - moderator permission required
        if (!empty($input['_set']['sticky']) && $this->_getForumModel()->canStickUnstickThreadInForum($forum))
        {
            $writer->set('sticky', $input['sticky']);
        }

        $postWriter = $writer->getFirstMessageDw();
        $postWriter->set('message', $input['message']);
        //$postWriter->setExtraData(XenForo_DataWriter_DiscussionMessage::DATA_ATTACHMENT_HASH, $input['attachment_hash']);
        $postWriter->setExtraData(XenForo_DataWriter_DiscussionMessage_Post::DATA_FORUM, $forum);
        $postWriter->setOption(XenForo_DataWriter_DiscussionMessage_Post::OPTION_MAX_TAGGED_USERS, $visitor->hasPermission('general', 'maxTaggedUsers'));

        $writer->setExtraData(XenForo_DataWriter_Discussion_Thread::DATA_FORUM, $forum);

        if ($pollInput['question'] !== '')
        {
            $pollWriter = XenForo_DataWriter::create('XenForo_DataWriter_Poll');
            $pollWriter->bulkSet(
                XenForo_Application::arrayFilterKeys($pollInput, array('question', 'multiple', 'public_votes'))
            );
            $pollWriter->set('content_type', 'thread');
            $pollWriter->set('content_id', 0); // changed before saving
            if ($pollInput['close'])
            {
                if (!$pollInput['close_length'])
                {
                    $pollWriter->error(new XenForo_Phrase('please_enter_valid_length_of_time'));
                }
                else
                {
                    $pollWriter->set('close_date', $pollWriter->preVerifyCloseDate(strtotime('+' . $pollInput['close_length'] . ' ' . $pollInput['close_units'])));
                }
            }
            $pollWriter->addResponses($pollInput['responses']);
            $pollWriter->preSave();
            $writer->mergeErrors($pollWriter->getErrors());

            $writer->set('discussion_type', 'poll', '', array('setAfterPreSave' => true));
        }
        else
        {
            $pollWriter = false;

            foreach ($pollInput['responses'] AS $response)
            {
                if ($response !== '')
                {
                    $writer->error(new XenForo_Phrase('you_entered_poll_response_but_no_question'));
                    break;
                }
            }
        }

        // TODO: check for required prefix in this node

        $spamModel = $this->_getSpamPreventionModel();

        if (!$writer->hasErrors()
            && $writer->get('discussion_state') == 'visible'
            && $spamModel->visitorRequiresSpamCheck()
        )
        {
            switch ($spamModel->checkMessageSpam($input['title'] . "\n" . $input['message'], array(), $this->_request))
            {
                case XenForo_Model_SpamPrevention::RESULT_MODERATED:
                    $writer->set('discussion_state', 'moderated');
                    break;

                case XenForo_Model_SpamPrevention::RESULT_DENIED;
                    $writer->error(new XenForo_Phrase('your_content_cannot_be_submitted_try_later'));
                    break;
            }
        }

        $writer->preSave();

        if ($forum['require_prefix'] && !$writer->get('prefix_id'))
        {
            $writer->error(new XenForo_Phrase('please_select_a_prefix'), 'prefix_id');
        }

        if (!$writer->hasErrors())
        {
            $this->assertNotFlooding('post');
        }

        $writer->save();

        $thread = $writer->getMergedData();

        if ($pollWriter)
        {
            $pollWriter->set('content_id', $thread['thread_id'], '', array('setAfterPreSave' => true));
            $pollWriter->save();
        }

        $spamModel->logContentSpamCheck('thread', $thread['thread_id']);
        $this->_getDraftModel()->deleteDraft('forum-' . $forum['node_id']);

        $this->_getThreadWatchModel()->setVisitorThreadWatchStateFromInput($thread['thread_id'], $input);

        $this->_getThreadModel()->markThreadRead($thread, $forum, XenForo_Application::$time);

        if (!$this->_getThreadModel()->canViewThread($thread, $forum))
        {
            $return = XenForo_Link::buildPublicLink('forums', $forum, array('posted' => 1));
        }
        else
        {
            $return = XenForo_Link::buildPublicLink('threads', $thread);
        }

        return $this->responseRedirect(
            XenForo_ControllerResponse_Redirect::SUCCESS,
            $return,
            new XenForo_Phrase('your_thread_has_been_posted')
        );
    }
I have used $upload = XenForo_Upload::getUploadedFile('UPL');
But it seems it never get any file with it???
 
Last edited:

Milano

Well-known member
Probably because your form have class AutoValidator, so the form will be submited via AJAX and you never get the file
 
Top