I want to upload my image using POST, but it always show an error while uploading the file ("There was an error uploading the file, please try again"). When I echo $link, only "uploaded//" appears.
How do I rename the "file" variable in $_FILES["file"] in my C# code?
variabel uriFotoAndr.Path return :
/storage/sdcard1/DCIM/Camera/MYIMAGE.jpg
C# Code :
System.Net.WebClient Client = new System.Net.WebClient();
Client.Headers.Add("Content-Type", "binary/octet-stream");
byte[] result = Client.UploadFile("my.web.com/ppl/post_image.php", "POST", uriFotoAndr.Path);
string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
Toast.MakeText(this, s, ToastLength.Long).Show();
PHP Code :
<?php
$uploads_dir = 'uploaded/';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
$link= $uploads_dir."/".$name;
if( move_uploaded_file($tmp_name, $link))
{
echo "Success: Picture Upload Successfully!";
}
else
{
echo "There was an error uploading the file, please try again!".$link;
}
}
else
{
echo "Error: Picture not Uploaded";
}
?>
I am using VS 2015 and Xamarin to build this app. Thanks in advance...
I already found the answer,
my web link on C# code before :
http://mywebsite.com/post_image.php
then i add "www" to the link :
http://www.mywebsite.com/post_image.php
and i can upload !!! :D
Related
I'm trying to use Unity to upload a .png file to a specific web folder. The issue could be 1 of 3 things.
1) I couldn't locate a php.ini file on godaddy. So could it be that the folder isn't configured for upload?
2) I've never done this in Unity before so it could be an issue with my code there. (it does return the message that my file couldn't be uploaded, so it is pinging the .php file)
3) It could also be the php code I have, not sure if I adapted the example properly.
I've read other examples but I'm just not sure where my issue even lies for what I should be fixing. Any advice would be awesome.
Unity:
public IEnumerator UploadTicketImage()
{
byte[] FileUpload = File.ReadAllBytes(Path.Combine(Application.persistentDataPath
+ "/TicketInformation/", "Pic001.png"));
WWWForm TextureForm = new WWWForm();
//TextureForm.AddBinaryData(PlayerPrefs.GetString("ImageName"), FileUpload);
TextureForm.AddBinaryData("TotalTest", FileUpload, Path.Combine(Application.persistentDataPath
+ "/TicketInformation/", "Pic001.png"),"image/png");
UnityWebRequest wwwimageupload = UnityWebRequest.Post(StaticVars.IPAddress+ "/UploadTicketsImage.php?", TextureForm);
wwwimageupload.uploadHandler = (UploadHandler)new UploadHandlerRaw(FileUpload);
//wwwimageupload.chunkedTransfer = false;
yield return wwwimageupload.SendWebRequest();
Debug.Log(wwwimageupload.downloadHandler.text);
}
PHP
<?php
$target_dir = "PhotoDeposit/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
?>
I would already expect it to not find the image file you want to upload correctly.
Path.Combine(Application.persistentDataPath + "/TicketInformation/", "Pic001.png")
results in a path like
| |
v v
C:\path\to\project\/TicketInformation/\Pic001.png
on windows or
| |
v v
/path/to/project//TicketInformation//Pic001.png
on linux or android.
It should rather be used like
Path.Combine(Application.persistentDataPath, "TicketInformation", "Pic001.png")
and
Path.Combine(Application.persistentDataPath, "TicketInformation")
The next point is: Why are you even using an UploadHandlerRaw when you already added the data to the WWWForm so this seems to make not much sense to me.
You should remove the line
wwwimageupload.uploadHandler = (UploadHandler)new UploadHandlerRaw(FileUpload);
Also note that File.ReadAllBytes only works on Windows platforms so depending on your build target you might have to change the way you read the file. You could use a UnityWebRequestTexture.GetTexture also to read local files. Something like
public IEnumerator UploadTicketImage()
{
var folderPath = Path.Combine(Application.persistentDataPath, "TicketInformation");
var filepath = Path.Combine(folderPath, "Pic001.png");
byte[] FileUpload = null;
using (var www = UnityWebRequestTexture.GetTexture(filepath))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.LogErrorFormat(this, "File loading failed with {0} - {1}", www.responseCode, www.error);
Debug.LogErrorFormat(this, "Couldn't read file at {0}", filepath);
yield break;
}
else
{
// file data successfully loaded
FileUpload = www.downloadHandler.data;
}
}
var form = new WWWForm();
// here you want the name the file should have on the server
// not a complete system path to file on your local device
// |
// |
// |
// And this is the field you will have |
// to access in php |
// | |
// v v
form.AddBinaryData("TotalTest", FileUpload, "Pic001.png", "image/png");
using (var www = UnityWebRequest.Post("https://111.111.111.1" + "/UploadTicketsImage.php?", form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.LogError(www.error);
}
else
{
Debug.Log(www.downloadHandler.text);
}
}
}
Finally I am no PHP expert by afaik you will then have to access the submitted field like
$_FILES['TotalTest']
sicne you call the field TotalTest in form.AddBinaryData.
Also the
if(isset($_POST["submit"]))
is probably never true since you didn't set it in the WWWForm (I might be wrong and it is set automatically whenever a request is sent).
Note: Typed on smartphone so no warranty but I hope the idea gets clear.
I'm trying to download files from my server through android using xamarin and I have no error but I don't find any file where it is supposed to be.
I'm using that code:
System.Net.WebClient Client = new System.Net.WebClient();
Console.WriteLine("Start downloading...");
try
{
var documentsFolder = System.Environment.GetFolderPath (System.Environment.SpecialFolder.MyDocuments);
if(!File.Exists(documentsFolder))
Directory.CreateDirectory(documentsFolder);
var fileNameAndPath = Path.Combine (documentsFolder, "tmpfile");
Client.DownloadFile(new Uri(url), fileNameAndPath);
}
catch(System.Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
while(e.InnerException!=null)
{
e=e.InnerException;
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
Console.WriteLine("...end downloading");
There's no error catched but no file downloaded, I tried several special paths but none seems to work. Can someone help me ?
//If the user uploaded an image, read it, and send it to the Vision API
if (activity.Attachments.Any() && activity.Attachments.First().ContentType.Contains("image"))
{
//stores image url (parsed from attachment or mess`enter code here`age)
string uploadedImageUrl = activity.Attachments.First().ContentUrl; ;
uploadedImageUrl = HttpUtility.UrlDecode(uploadedImageUrl.Substring(uploadedImageUrl.IndexOf("file=") + 5));
using (Stream imageFileStream = File.OpenRead(uploadedImageUrl))
{
try
{
analysisResult = await visionClient.AnalyzeImageAsync(imageFileStream, visualFeatures);
}
catch (Exception e)
{
analysisResult = null; //on error, reset analysis result to null
}
}
}
//Else, if the user did not upload an image, determine if the message contains a url, and send it to the Vision API
else
{
try
{
analysisResult = await visionClient.AnalyzeImageAsync(activity.Text, visualFeatures);
}
catch (Exception e)
{
analysisResult = null; //on error, reset analysis result to null
}
}
I am trying the code above. I got the code from here: https://docs.botframework.com/en-us/bot-intelligence/vision/#example-vision-bot.
As is, the code does what it can do when ran locally, but reading the image's URL from an uploaded file doesn't work after I published my bot to Azure and ran it from there.
I attempted to debug by attaching Visual Studio directly to my published webapp bot in Azure. It looked like the webapp is unable read the stored image's URL from the Azure server temp storage location or can't access the temp storage location.
This line:
uploadedImageUrl = HttpUtility.UrlDecode(uploadedImageUrl.Substring(uploadedImageUrl.IndexOf("file=") + 5));
Shows this value:
"https://bcattachmentsprod.blob.core.windows.net/at4984/Gv4cOx6OdSl- original"
Then, this line:
using (Stream imageFileStream = File.OpenRead(uploadedImageUrl))
Changes the value to:
"s://bcattachmentsprod.blob.core.windows.net/at4984/Gv4cOx6OdSl-original"
And then it just stops.
Has anyone ran into an issue like this? How do I go about solving this issue?
Thanks!
If you have a image URL, you should simply call AnalyzeImageAsync with that URL instead of creating a stream as you have. The File class should be used for files on your local drive/network. By creating a stream, you download the image once to your VM, then upload it to the vision service, doubling the work.
Hi I have been making an app in Unity and I have been trying to add code that will log User actions i.e. they have made a certain game object appear. What I am trying to do is write to a .txt file stored on a server I have the following code which is based on:
http://answers.unity3d.com/questions/984290/upload-txt-file-to-server-using-php.html
and they suggest it works, for me it is not writing anything to the file.
Here is my PHP code (SaveData.php):
<?php
$Action = $_GET["action"];
$Date = date('Y/m/d H:i:s');
$myFile = "TestingData.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh,$Action . "," . $Date . "\n");
fclose($fh);
?>
And here is the C# (SaveData.cs) I am attaching to the game objects I change the Action value in the inspector window:
using UnityEngine;
using System.Collections;
public class SaveData : MonoBehaviour {
public string postDataURL = "http://arinstructionman.byethost7.com/SaveData.php?"; //add a ? to your url
public string Action;
void Start()
{
StartCoroutine(PostData(Action));
}
IEnumerator PostData(string action)
{
string post_url = postDataURL + "action=" + WWW.EscapeURL(action);
WWW data_post = new WWW(post_url);
yield return data_post;
if (data_post.error != null)
{
print("There was an error saving data: " + data_post.error);
}
}
}
If I copy the post_url value and run it in the browser it seems to work fine, can anyone advise what I am doing wrong?
post_url output:
http://arinstructionman.byethost7.com/SaveData.php?action=Plane+Visible
Any help is much appreciated.
I would suggest trying this with $_POST instead of $_GET and see if you get a different response.
Also, you can use file_put_contents to open, write, and close the file all in one line, and using the FILE_APPEND flag to prevent overwriting the existing file. If the file does not exist, this will also create the file for you.
<?php
if(!isset($_POST["action"]))
{
echo ("NO DATA RECIEVED");
return;
}
$action = $_POST["action"];
$date = date('Y/m/d H:i:s');
$data = "{$action},{$date}\n";
$myFile = "TestingData.txt";
if(file_put_contents($myFile, $data, FILE_APPEND))
echo ("success");
else
echo ("failed to write file);
?>
And use WWWform to POST data to the PHP file:
public string postDataURL = "http://arinstructionman.byethost7.com/SaveData.php";
public string Action = "some action";
void Start()
{
StartCoroutine(PostData(Action));
}
IEnumerator PostData(string action)
{
WWWForm form = new WWWForm();
form.AddField("action", action);
WWW dataPost = new WWW(postDataURL, form);
yield return dataPost;
if (dataPost.error != null)
print("There was an error saving data: " + data_post.error);
else
print(dataPost.text);
}
)
Just in case someone is trying to implement that and it doesn't work like it was the case for me.
I found a fix, for sure is not the best implementation, but at least it works for the moment :
If your server doesn't use PHP5 you will have to use PHP4 function
(coming from : http://memo-web.fr/categorie-php-126/ ):
function file_put_contents_PHP4($myFile, $data) {
$f = #fopen($myFile, 'w');
if (!$f) {
echo ("failed to write file");
return false;
} else {
$resultat= fwrite($f, $data);
fclose($f);
echo ("success");
return $resultat;
}
}
For sure we could test if PHP5 is available with something like, but my php knowledge is kind of bad ahah :
if (!function_exists('file_put_contents'))
{
function file_put_contents_PHP4...
{
The Scripts :
SaveData.php, in your server online:
<?php
$action = $_POST["action"];
$data = "{$action}";
$myFile = "TestingData.txt";
if($action == "")
{
echo ("NO DATA RECIEVED");
return;
}
else
file_put_contents_PHP4($myFile, $data);
function file_put_contents_PHP4($myFile, $data) {
$f = #fopen($myFile, 'w');
if (!$f) {
echo ("failed to write file");
return false;
} else {
$resultat= fwrite($f, $data);
fclose($f);
echo ("success");
return $resultat;
}
}
?>
Unity c# Script :
[SerializeField] private string postDataURL = "http://yourebsite.com/SaveData.php";
[SerializeField] private string Action = "some action";
void Start()
{
StartCoroutine(PostData(Action));
}
IEnumerator PostData(string action)
{
WWWForm form = new WWWForm();
form.AddField("action", action);
WWW dataPost = new WWW(postDataURL, form);
yield return dataPost;
if (dataPost.error != null)
print("There was an error saving data: " + dataPost.error);
else
print(dataPost.text);
}
Don't forget to put an empty text file "TestingData.txt" next to "SaveData.php" into the server.
Don't forget as well to add the correct adress to SaveData.php in the Inspector.
I uploaded them to an old personal server using Filezilla and everything is working as intended.
Cheers :-)
I am new to Telerik controls, in my code I am trying to Upload excel file using RadAsync upload.
Code is working fine, but when user is trying to upload a file which is already opened in the background- I am getting javascript exception.
Is there is any way by which I can alert user in case file is already opened?
You can use OnClientFileUploadFailed event of Telerik RadAsync Upload.
Something like
function OnClientFileUploadFailed(sender, args) {
var upload = $find("<%= RadUpload.ClientID %>");
var errormsg = args.get_message();
var displaymsg = new String();
sender.deleteFileInputAt(0);
if (errormsg.search("[IO.IO_SharingViolation_File]") != -1) {
displaymsg = "File: is currently in use. Please close the file and try again.";
}
else {
displaymsg = "The file you selected is currently in use. Please close the file and try again.";
}
alert(displaymsg);
args.set_handled(true);
}