- Home /
Uploading photo and video on a web server
First, I would like to mention that I am developing an electronic tour of our school that will be deployed on many desktop computers. In each client, the admin can access all the administrative tools by logging in. So if the admin for example want to add an information about a building, that information will be uploaded to a web server(I am using apache, mysql, and php) using one of the deployed client and the info will be save to mysql via php. And also one of the requirement of the system is to be able to load a photo or video on local file system of one of the client and then upload it to the web server(installed on one of the computer in the LAN).
So far the system can upload text information. What I'm having trouble with, is the uploading of photos and videos. Any tips, links, or tutorials on how to achieve this will be greatly appreciated.
Btw, I already search on google on how to achieve this, but no luck so far.
Hi Guys,
You can use this plugin Easy Downloader and Uploader
Hey,
Im pretty new to WWW/UnityWebRequest and PHP, and im working on it for school project atm.
I have been trying to upload a video to a server through a post request with php, When i do the post request with Postman it works fine. When i do it through unity it returns that the file is empty, (while my byte[] i have is filled) I wonder if you had the same problem or if it is not at all related.
Answer by Bunny83 · Feb 21, 2011 at 03:16 PM
Use the WWW class to open/load the local file or use System.IO stuff for reading.
To upload the file to your webpage use WWWForm along with WWW. There's even an example of how to upload a screenshot on the WWWForm reference page. I guess you're familiar with the backend part (php, mysql).
SECOND EDIT:
// C# file names: "FileUpload.cs" using UnityEngine; using System.Collections;
public class FileUpload : MonoBehaviour { private string m_LocalFileName = "C:/boot.ini"; private string m_URL = "http://192.168.178.29/php/upload.php";
IEnumerator UploadFileCo(string localFileName, string uploadURL)
{
WWW localFile = new WWW("file:///" + localFileName);
yield return localFile;
if (localFile.error == null)
Debug.Log("Loaded file successfully");
else
{
Debug.Log("Open file error: "+localFile.error);
yield break; // stop the coroutine here
}
WWWForm postForm = new WWWForm();
// version 1
//postForm.AddBinaryData("theFile",localFile.bytes);
// version 2
postForm.AddBinaryData("theFile",localFile.bytes,localFileName,"text/plain");
WWW upload = new WWW(uploadURL,postForm);
yield return upload;
if (upload.error == null)
Debug.Log("upload done :" + upload.text);
else
Debug.Log("Error during upload: " + upload.error);
}
void UploadFile(string localFileName, string uploadURL)
{
StartCoroutine(UploadFileCo(localFileName, uploadURL));
}
void OnGUI()
{
GUILayout.BeginArea(new Rect(0,0,Screen.width,Screen.height));
m_LocalFileName = GUILayout.TextField(m_LocalFileName);
m_URL = GUILayout.TextField(m_URL);
if (GUILayout.Button("Upload"))
{
UploadFile(m_LocalFileName,m_URL);
}
GUILayout.EndArea();
}
}
I have a xitami webserver on a windows machine(actually a very old laptop with Win98 :D) and use this php script:
<?php if(isset($_FILES['theFile'])) { print("Success! "); print("tmpName: " . $_FILES['theFile']['tmp_name'] . " "); print("size: " . $_FILES['theFile']['size'] . " "); print("mime: " . $_FILES['theFile']['type'] . " "); print("name: " . $_FILES['theFile']['name'] . " ");
move_uploaded_file($_FILES['theFile']['tmp_name'], "../images/" . $_FILES['theFile']['name']);
} else { print("Failed!"); } ?>
...and it works great. In Unity i get this as result:
version 1:
upload done :Success! tmpName: C:\WINDOWS\TEMP\php2291.TMP size: 212 mime: application/octet-stream name: theFile.dat
version 2:
upload done :Success! tmpName: C:\WINDOWS\TEMP\php11B2.TMP size: 212 mime: text/plain name: boot.ini
Thanks for the reply, and the sample code helps me a lot. Now, I can move on how to handle think inside php. But when I think about it, the file is inside the $_POST variable. Well I'm familiar of moving files around from temporary files in the web server to any directory in the web root using $_FILES variable but not $_POST, so my question is how to save the file inside the $_POST to any directory in the web root. Again any tips on how to do this will be appreciated.
hmm, well, that sounds like a pure php problem and i'm not that familiar with php ;) just have done some basic things and had to look up a lot. $$anonymous$$aybe someone else have more experience with uploading files and php processing. In general is it a problem when the "file data" comes in a post var? I don't know it that really happens, i think the file will still be in $_FILES. Just take a look at this: http://www.tizag.com/phpT/fileupload.php
AddBinaryData just adds a new field to the post data like in HT$$anonymous$$L. $$anonymous$$y example just generate a field like this: The real file name and mime type can also be specified. Look at http://unity3d.com/support/documentation/ScriptReference/WWWForm.AddBinaryData.html
Thanks for the research, I really appreciated it. I'm now convince that the uploaded file is actually on the $_FILES. And I Wrote a php sciprt to prove it:
if(isset($_FILE['theFile']))
{
echo "Success!";
}
else
{
echo "Failed!";
}
?>
No matter how I check the code in C# and PHP, I can't find something wrong, but the php code kept returning "Failed!". And I also test this script with $_POST and $_GET, and they also return "Failed!". I've also check the file local address, and it is valid. If you have an idea why, it will be greatly appreciated.
I just tried it and it works great, after reading your last comment again, i've spotted your mistake: it's $_FILES ins$$anonymous$$d of $_FILE
Answer by Sanlaato · Feb 22, 2011 at 10:14 AM
I check it numerous times, but I doesn't make sense to me why it kept returning "Failed!". So I decided to post my test code here.
Here's my C# test code
//C# using UnityEngine; using System.Collections;
public class Test : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI()
{
GUI.Label(new Rect(100, 0, 500, 20), Application.dataPath);
if (GUI.Button(new Rect(100, 100, 150, 20), "Upload"))
{
UploadFile("http://localhost/image.php");
}
}
IEnumerator UploadFileCo(string uploadURL)
{
WWW localFile = new WWW("file://G:/0001.png");
yield return localFile;
WWWForm postForm = new WWWForm();
postForm.AddBinaryData("file", localFile.bytes, "0001.png", "image/png");
WWW upload = new WWW(uploadURL, postForm);
yield return upload;
if (upload.error == null)
{
Debug.Log(upload.text);
}
else
{
Debug.Log("Error during upload: " + upload.error);
}
}
void UploadFile(string uploadURL)
{
StartCoroutine(UploadFileCo(uploadURL));
}
}
And here's my php code
<?php
$thefile = $_FILES['file'];
if(!empty($theFile))
{
echo "Success!";
}
else
{
echo "Failed!";
}
?>
Any help about why it kept returning "Failed!" and how to fix it will be appreciated.
After retyping all of the code, it finally works. From here on out, I think I can manage. Thanks for all the help Bunny83. :)
Hmm, strange, are you sure the local file can be loaded? I've read somewhere that "file://" won't work in all cases and you should use "file:///". Are you sure your webserver/phpconfig allows uploads? If not that would explain the "failed". In my "new" example i've added some more error checking to the coroutine. The error checking on php side could be better but it works for me ;)
Great, you solved it. Anyway, now i have a working example for my future projects ;)
Ohh, and please don't use answers as comments. If you have new information you can edit your question.
Answer by TechnoAdiict · Dec 18, 2017 at 03:16 PM
php is wrong in above code : @Sanlaato $thefile variable case
$thefile = $_FILES['file']; if(!empty($thefile)) {
echo "Success!"; } else {
echo "Failed!"; }
Answer by junedmmn · May 08, 2019 at 11:12 AM
Smallest and easy Solution is using UnityWebRequest, as WWW is obsolete. This will work in latest and upcoming Unity Versions
using UnityEngine.Networking;
public IEnumerator PostImageToPhp()
{
var file = UnityWebRequest.Get("file://C:/star.png");
yield return file;
WWWForm form = new WWWForm();
form.AddBinaryData("file", file.downloadHandler.data);
var upload = UnityWebRequest.Post("http://localhost/Sample/GetFile.php", form);
yield return upload.SendWebRequest();
if (upload.isHttpError)
Debug.Log(upload.error);
else
Debug.Log("Uploaded Successfully");
Debug.Log(upload.downloadHandler.text); // display whether Server got the File
}
PHP Code
<?php
$file = $_FILES["file"];
if (!empty($file))
echo "Got file";
else
echo "Failed to get File";
?>
is only that php code neccesary? or Do I need to add something else?
Always get error HTTP/1.1 400 Bad Request
Could you help me please?
Answer by sebastiao_lucio · Oct 16, 2019 at 10:22 AM
@Sanlaato Try this asset http://u3d.as/1DxF we created this asset to solve this problem and much more!any doubt : https://forum.unity.com/threads/released-basic-web-request-pro-1-0-http-post-and-get-requests-to-a-web-server-php-and-nodejs.761489/