[英]PHP - uploading images and $_files variable
我正在為博客文章創建一個帶有 WYSIWYG 編輯器的博客,並為每篇博客文章上傳圖片。
所以我的輸入看起來像這樣,我在這里包含了一個名為wysiwyg.php
的文件,但這對於這個問題並不是真正必要的。 (它基本上有用於粗斜體等的按鈕,它只是這樣包含,因為我在我網站的其他區域使用它)
<form action="blog_create.php" method="POST">
<input id="title" name="title" type="text" placeholder="Title">
<input id="post_image" name="post_image" type="file">
<textarea id="description" name="description" placeholder="Description"></textarea>
<textarea id="meta" name="meta" placeholder="Meta"></textarea>
<div id="wysiwyg_controls"><?php include_once("wysiwyg.php"); ?></div>
<iframe name="richTextField" id="wysiwyg" class="news_article"></iframe>
<input type="hidden" id="text_content" name="text_content" value="">
<input type="hidden" id="save_as_type" name="save_as_type" value="">
<button id="blog_draft_submit" name="blog_draft_submit" onclick="return false">Save as Draft</button>
<button id="blog_publish_submit" name="blog_publish_submit" onclick="return false">Publish</button>
</form>
然后我使用 JavaScript/jQuery 像這樣提交表單以實際獲取 iframe 的內容:
$("#blog_draft_submit").on("click", function(){
$text_content = richTextField.document.getElementsByTagName('body')[0].innerHTML;
$("#text_content").attr("value", $text_content);
$("#save_as_type").attr("value", "draft");
this.form.submit();
});
$("#blog_publish_submit").on("click", function(){
$text_content = richTextField.document.getElementsByTagName('body')[0].innerHTML;
$("#text_content").attr("value", $text_content);
$("#save_as_type").attr("value", "publish");
this.form.submit();
});
但是,這似乎不適用於文件輸入或無法訪問應在 Global $_FILES
變量中的任何內容。
如果我做var_dump($_FILES);
我得到:
array (size=0)
empty
但是當我做var_dump($_POST);
我得到:
array (size=8)
'title' => string '' (length=0)
'post_image' => string 'image.png' (length=23)
'description' => string '' (length=0)
'meta' => string '' (length=0)
'wysiwyg_image' => string '' (length=0)
'text_content' => string '' (length=0)
'save_as_type' => string 'draft' (length=5)
這是因為我通過 JS 提交的方式還是我實際上做錯了什么? 我是否需要創建一個單獨的解析文件並執行XMLHttpRequest
和類似 AJAX 的操作?
不需要 AJAX。
嘗試在<form>
標簽中添加enctype="multipart/form-data"
當我們使用$_FILE
時要遵循的一些規則:
- 檢查 php.ini 文件上的
file_uploads = On
- 確保表單使用 method="post"
- 表單還需要以下屬性:
enctype="multipart/form-data"
(它指定提交表單時使用的內容類型)
如果沒有上述要求,文件上傳將無法進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.