javascript Wordpress 中的前端媒体上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9160979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Front End Media Uploading in Wordpress
提问by ninja
I'm in need of some help! :)
我需要一些帮助!:)
What I'm trying to do is let a user create a post from the front end. With a preview window of how the post will look like when published. This I have already accomplished. Now I'm trying to allow the user to upload a image directly into the media library. This upload needs to happen as soon as the user has chosen the file with the follow code:
我想要做的是让用户从前端创建一个帖子。带有帖子发布后外观的预览窗口。这我已经完成了。现在我试图允许用户将图像直接上传到媒体库中。一旦用户选择了具有以下代码的文件,就需要进行此上传:
<form method="post" action="#" enctype="multipart/form-data" >
<input type="file" name="featured_image">
</form>
I don't want any page load, is there a way to get the file without using a submit button? Also how do I handle the actual file upload, my google skills found this function:
我不想加载任何页面,有没有办法在不使用提交按钮的情况下获取文件?另外我如何处理实际的文件上传,我的谷歌技能发现了这个功能:
function insert_attachment($file_handler,$post_id,$setthumb='false') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
But this function hooks the upload to a post, I just want it to go straight into the library without being connected to a post. Also I assume the $file_handler is the name of the form? I also assume that $_FILES doesn't exists unless the user has clicked a submit button.
但是这个函数将上传挂钩到一个帖子,我只是想让它直接进入库而不连接到一个帖子。另外我假设 $file_handler 是表单的名称?我还假设 $_FILES 不存在,除非用户点击了提交按钮。
I'm prolly way off here, talking out of my ass. So any help would be appriciated. Any WP-gurus available? :D
我快要离开这里了,胡说八道。因此,任何帮助都会受到重视。有可用的 WP 大师吗?:D
采纳答案by ninja
Ok, I'm getting forward. I'm now using this jquery plugin for image uploading -> http://lagoscript.org/jquery/upload
好的,我要前进了。我现在使用这个 jquery 插件来上传图片 -> http://lagoscript.org/jquery/upload
Which is very lightweight and works great. Uploads the image to my computer without refreshing. It saves the file in a temp dir on my server, what I'm planning to do now is somehow inject this image into the media library (and then delete it from the temp folder), but this seems harder than it should.
它非常轻巧,效果很好。将图像上传到我的电脑而不刷新。它将文件保存在我服务器上的临时目录中,我现在打算以某种方式将此图像注入媒体库(然后从临时文件夹中删除它),但这似乎比它应该的要难。
Is there any way I can add a image to the media library with php-code, using only a image url? I can't seem to find one, but since WP has this feature in the admin-area already there must be a way.
有什么方法可以使用 php 代码将图像添加到媒体库中,只使用图像 url?我似乎找不到一个,但是由于 WP 在管理区域中已经具有此功能,因此必须有一种方法。
The easiest way seems to be just creating a custom field that stores the image for that post, but I really want to be able to use WPs thumbnail functions, not only for looping, but for resizing etc.
最简单的方法似乎只是创建一个自定义字段来存储该帖子的图像,但我真的希望能够使用 WPs 缩略图功能,不仅用于循环,还用于调整大小等。
Any pointers?
任何指针?
回答by prumand
I had the same problem. The Wordpress Documentation helps: http://codex.wordpress.org/Function_Reference/wp_handle_uploadhttp://codex.wordpress.org/Function_Reference/wp_insert_attachment
我有同样的问题。Wordpress 文档有帮助:http: //codex.wordpress.org/Function_Reference/wp_handle_uploadhttp://codex.wordpress.org/Function_Reference/wp_insert_attachment
UPDATE: $key is the name of the type="file"
更新:$key 是 type="file" 的名称
I just added the guid value, because it doesn't seem to be added (and maybe there are better ways, then including admin.php:
我只是添加了 guid 值,因为它似乎没有添加(也许有更好的方法,然后包括 admin.php:
require_once(ABSPATH . 'wp-admin/includes/admin.php');
// step one upload file to server
$file_return = wp_handle_upload($_FILES[$key], array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
echo 'not working again :(';
}
else {
/**
* See http://codex.wordpress.org/Function_Reference/wp_insert_attachment
*
*/
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attach_id = wp_insert_attachment( $attachment, $file_return['url'] );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
回答by Prakash Adhikari
I am using this code working is fine
我正在使用此代码工作正常
javascript
javascript
<script src="<?php bloginfo( 'template_url' ); ?>/image_file/jquery.ui.widget.js"></script>
<script src="<?php bloginfo( 'template_url' ); ?>/image_file/jquery.iframe-transport.js"></script>
<script src="<?php bloginfo( 'template_url' ); ?>/image_file/jquery.fileupload.js"></script>
<script src="<?php bloginfo( 'template_url' ); ?>/image_file/jquery.fileupload-validate.js"></script>
<script>
$(function () {
'use strict';
var url = '<?php bloginfo( 'template_url' ); ?>/upload.php';
$('#fileupload').fileupload({
add: function(e, data) {
var uploadErrors = [];
if(data.originalFiles[0]['size'] > 2000000) {
uploadErrors.push('Filesize is too big');
}
if(uploadErrors.length > 0) {
$("#errormessage").show();
$("#errormessage").html(uploadErrors.join("\n"));
} else {
data.submit();
$("#errormessage").hide();
}
},
url: url,
dataType: 'json',
done: function (e, data) {
if(data._response.result.response=="errortype"){
$("#errormessage").show();
$("#errormessage").html("Not an accepted file type ");
$("#progress").hide();
}
else
{
$("#progress").show();
var url=data._response.result.upload_info.url;
if(url=='')
{
}
$("#file_url").val(url);
}
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').html( progress + '%');
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
HTML
HTML
<
<
span class="input__label-content input__label-content--akira" >UPLOAD A PHOTO OF YOUR RECEIPT**</span>
<span id="fileupload"> <input type="file" name="upload_file" multiple></span>
</span>
<input type="hidden" name="file_url" value="" id="file_url" />
upload.php
<?php
require("../../../wp-load.php");
global $wpdb;
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfiles = $_FILES['upload_file'];
if(strtolower($uploadedfiles['type'])=='image/jpeg' || strtolower($uploadedfiles['type'])=='image/gif' || strtolower($uploadedfiles['type'])=='image/png' || strtolower($uploadedfiles['type'])=='image/pjpeg' || strtolower($uploadedfiles['type'])=='image/x-png'){
//
$upload_overrides = array( 'test_form' => false );
$results=array();
if ($uploadedfiles['name']) {
$file = array(
'name' => $uploadedfiles['name'],
'type' => $uploadedfiles['type'],
'tmp_name' => $uploadedfiles['tmp_name'],
'error' => $uploadedfiles['error'],
'size' => $uploadedfiles['size']
);
$movefile = wp_handle_upload( $file, $upload_overrides );
if ( $movefile ) {
$data=array('result'=>'success','upload_info'=>$movefile);
$filename = $movefile['upload_file']['file'];
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
} else {
$data=array('result'=>'error','upload_info'=>null);
}
$data['request']=$_FILES;
}
}
else
{
$data=array('response'=>'errortype','upload_info'=>null);
}
echo json_encode($data);
?>