简体   繁体   English

使用javascript上传图片

[英]uploading image using javascript

I'm stuck!! 我被困了!! :( I want to upload image file with a title and a caption, I want to use javascript for validation of title caption and a file choosen. :(我想上传带有标题和标题的图像文件,我想使用javascript验证标题标题和文件选择。

My html goes here: 我的HTML在这里:

<input type="text" name="title2" id="title2" value="title" /><br />

<textarea cols="50" rows="10" name="caption" >caption goes here...</textarea><br />
<input type="file" name="photo" id="photo" /><br />
<button id="submit_info" onclick="photowcap()" >post</button><br />

and my javascript here: 和我的javascript在这里:

function photowcap()
{

var title = document.getElementsByName("title2")[0].value;
var photo = document.getElementsByName("photo")[0].value;
var captions = document.getElementsByName("caption")[0].value;
var caption = encodeURIComponent(captions)

var xmlhttp;
if(title == "" || title == " " || title == "title")
{
    document.getElementsByName("title2")[0].focus();
    document.getElementsByName("title2")[0].value="";
    return;
}
else if(captions == "" || captions == " " || captions == "caption goes here..."){
    document.getElementsByName("caption")[0].focus();
    document.getElementsByName("caption")[0].value="";
    return;
}
else if(photo == ""){
    alert("please choose image");
}
else{
if (window.XMLHttpRequest)
{
    xmlhttp=new XMLHttpRequest();
}
else
{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            alert("Success!!!");
        }
    }
xmlhttp.open("GET","photowcap.php?    title="+title+"&caption="+caption+"&photo="+photo,true);
    xmlhttp.send();}

}

And for saving it using php: 并使用PHP保存它:

<?php

include("admin_conn.php");

$title = $_GET["title"];
$caption = $_GET["caption"];
$photo = $_GET["photo"];
$time=time();
$date = (date("D F d Y",$time));

$query_photowcap = "INSERT INTO school_updates(title, photo, caption, date, time)     VALUES('$title','$photo','$caption','$date','$time')";
mysql_query($query_photowcap);

?>

it only save for the file path as "C:fakepath/filename...." because I dont have any idea on how to get filename using javascript, and finally I have this code for saving the actual image into the folder but I dont really get where I should place it: THANKS IN ADVANCE :) 它只保存文件路径为“C:fakepath / filename ....”因为我不知道如何使用javascript获取文件名,最后我有这个代码将实际图像保存到文件夹但我不真的得到我应该放置的地方:感谢提前:)

<?php

error_reporting(0);
$max_file_size = 200 * 1024; #200kb
if (($_FILES["photo"]["type"] == "image/gif")
  || ($_FILES["photo"]["type"] == "image/jpeg")
  || ($_FILES["photo"]["type"] == "image/png" )
  && ($_FILES["photo"]["size"] < $max_file_size))
  {
  $path = 'images/' . uniqid();
  move_uploaded_file($_FILES["photo"]["tmp_name"],
  $path.$_FILES["photo"]["name"]);

  }
else
  {
  echo "Files must be either JPEG, GIF, or PNG and less than 200 kb";
  }

?>

In order to access files with the $_FILES superglobal they need to be sent with a multipart/form-data content-type header and appropriate attributes. 为了使用$_FILES超全局访问文件,需要使用multipart/form-data内容类型标头和适当的属性发送它们。 Unfortunately you cannot do this with xhr 's send method manually because sending a string will be automatically converted to UTF-8 . 不幸的是你不能手动使用xhr的send方法,因为发送字符串将自动转换为UTF-8 Fortunately though you can still send binary data such as a file from javascript's window.File . 幸运的是,您仍然可以从javascript的window.File发送二进制数据,例如文件。文件。

This is not supported in older browsers. 旧版浏览器不支持此功能。 The code would look like 代码看起来像

var file = document.getElementById('photo').files[0];

...

xhr.send(file);

And then on the server side you will need to access the input buffer directly in order to grab a hold of this file 然后在服务器端,您将需要直接访问输入缓冲区以获取此文件的保留

$file = file_get_contents('php://input');

If you insist on using $_FILES you could use the FormData object in javascript. 如果你坚持使用$_FILES你可以在javascript中使用FormData对象。 The reason I left this as a second option is because I've heard about greater support issues and I personally avoid using it for now. 我之所以选择这个作为第二种选择,是因为我听说过更多的支持问题而且我个人现在避免使用它。

var formData = new FormData(document.getElementById('theForm'));
...
xhr.send(formData);

EDIT 2016 编辑2016

It has been some time now since I posted this answer and now the FormData object is widely supported, if you are looking to upload files along with other data you may look into that. 现在已经有一段时间了,因为我发布了这个答案,现在广泛支持FormData对象,如果您希望上传文件以及其他数据,您可以查看它。

You are trying to upload an image with ajax... short answer... normally you can't. 您正在尝试使用ajax上传图像...简短回答...通常您不能。 You need a multipart/form-data to upload, making ajax upload a pain. 您需要上传多部分/表单数据,使ajax上传变得困难。

An easy work around would be to validate the form with js, then normally submit it. 一个简单的解决方法是用js验证表单,然后通常提交它。 Like here: Ajax Upload image - well... ignore the title, is misleading. 像这里: Ajax上传图片 - 好吧......忽略标题,有误导性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM