I don't know how to access folder "Images" on android devies, to send file directly to it.
I'm able to successfully send file using below code, however after research I'm not able to specify "Uri" so I can't receive file in "Image" folder or any other than "Download" which is i think default.
var file = #"C:\Users\JDOMINO\Desktop\Personal\Zegarek\1.jpg";
var uri = new Uri("obex://" + device.DeviceAddress + "/" + file);
var request = new ObexWebRequest(uri);
request.ReadFile(file);
var response = (ObexWebResponse)request.GetResponse();
MessageBox.Show(response.StatusCode.ToString());
// check response.StatusCode
response.Close();
Expected output would be something like to change Uri from "obex://" to "obex://Images/Newfolder" however this doesn't work.
Related
I have a script that uploads a video to an API I built, and after it processes on the API side, a text file is returned to the client. The strange thing is, this only works with one type of file, a .QT file extension. Any other video type I try to send sends and empty video. I have tried .mov, .mp4, and .qt and only the .qt uploads properly. I'll post my code below. Would anyone know what cause only the one file type to work? Nothing on the API side singles out the qt file. I believe this is an issue with this script.
public async void Function() {
Debug.Log("works1");
string filePath = "IMG_0491.mov";
//string filePath = ProcessMode.theFilePath;
var client = new HttpClient();
using (var multipartFormContent = new MultipartFormDataContent()) {
//Add the file
Debug.Log("works2");
var fileStreamContent = new StreamContent(File.OpenRead(filePath));
Debug.Log("works3");
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("video/mov");
multipartFormContent.Add(fileStreamContent, name: "file", fileName: filePath); //Originally Actual "Name`
//Send it
var response = await client.PostAsync("http://127.0.0.1:5000/", multipartFormContent); //Enter IP and Port of API when set up
Debug.Log("works4");
//Ensure it was successful.
response.EnsureSuccessStatusCode();
//Grab the animation data from the content.
var animation_data = await response.Content.ReadAsStringAsync();
Debug.Log(animation_data);
//Save to file.
//File.WriteAllTextAsync("AnimationFile.txt", animation_data);
await File.WriteAllTextAsync("AnimationFile.txt", animation_data);
Debug.Log("works5");
}
Currently trying to convert a curl command to Unity Web request
Curl Command:
curl -H “x-app-key:APP_KEY_HERE“ /
-F " file=#AudioFile.wav" /
-F "user_token=USER_TOKEN_HERE" /
-F "category=orange" /
https://api.soapboxlabs.com/v1/speech/verification
And the code I've attempted:
private string url = "https://api.soapboxlabs.com/v1/speech/verification";
private string apiKey = "123456789";
void Start()
{
StartCoroutine(MakeSoapboxRequest());
}
IEnumerator MakeSoapboxRequest()
{
List<IMultipartFormSection> form = new List<IMultipartFormSection> {
new MultipartFormFileSection("file", "Assets\\Pilot1\\Audio\\soapbox_test.wav"),
new MultipartFormDataSection("user_token", "aaa1234567"),
new MultipartFormDataSection("category", "orange")
};
UnityWebRequest request = UnityWebRequest.Post(url, form);
request.SetRequestHeader("x-app-key", apiKey);
yield return request.SendWebRequest();
if(request.isNetworkError || request.isHttpError)
{
Debug.LogError(request.error);
}
else
{
Debug.Log("No soapbox error");
Debug.Log(request.downloadHandler.text);
}
}
Keep getting an error HTTP/1.1.400 Bad request
As you can see I've tried and commented out, WWW form as well. Is it something to do with me sending the wav file? I've tried looking into sending it as bytes but was left confused. The API I'm sending it to only takes wav files. It returns a JSON file. I'm just using the downloadHandler.text as a test.
Any help would be appreciated. I haven't used CURL before and it's my first time trying Unity Web Requests.
Note that the overload you are using for the file is MultiPartFormFileSection(string data, string fileName)
and states
data: Contents of the file to upload.
fileName: Name of the file uploaded by this form section.
So what happens here is: You are trying to upload "file" as the file content in an anonymous file section.
I think you should rather get the actual byte[] and rather use the overload MultipartFormFileSection(string name, byte[] data, string fileName, string contentType)
name Name of this form section.
data Raw contents of the file to upload.
fileName Name of the file uploaded by this form section.
contentType The value for this section's Content-Type header.
e
e.g. like
// Of course you would probably do these async before running the routine to avoid freeze
string yourFilePath;
var bytes = File.ReadAllBytes(yourFilePath);
new MultipartFormFileSection("file", bytes, "soapbox_test.wav", "application/octet-stream")
Finally note:
While a path like your given Assets\Pilot1\Audio\soapbox_test.wav might or might not work in the Unity Editor it will definitely fail in a build application!
You should either put your file into the StreamingAssets folder and access it via
var filePath = Path.Combine(Application.streamingAssetsPath, "fileName.extension");
or use the PersistentDataPath (you would of course have to make sure your file is stored there first)
var filePath = Path.Combine(Application.persistentDataPath, "fileName.extension");
I have found some answers here that give examples but none seems to work for me..
this is how my postman looks:
In the code I download the picture from a URL, save it as jpeg inside a folder and then I try to upload that image with a POST request, here is how it looks:
var fileName = image.PhotoId + ".jpeg";
await Task.WhenAll(client.DownloadFileTaskAsync(new Uri(image.ImageUrl), #"wwwroot\images\"+fileName));
var files = Directory.GetFiles(#"wwwroot\images\", "*.jpeg");
var filePath = Path.Combine(#"wwwroot\images\", fileName);
using var stream = File.OpenRead(filePath);
var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
var formData = new MultipartFormDataContent();
formData.Add(file_content, "file", fileName);
var res = await clientAsync.PostAsync(url, formData);
problem is the response that I get in the code is an error..:
{"error_code":6,"error_message":"Sorry, please try a different picture"}
this type of response is the same one I get when trying to upload a pdf instead of a jpeg on postman so I guess the file is getting corrupted in the code somewhere.
would love to get any ideas to where the problem is!
I can upload images to Slack via my SlackAPI and I can upload files and I can upload images with comments - but I can not do this with files that are no images.
I'm sure it's a problem with my message-structure - have a look: All this is done via HttpClient!
This is my working fileUpload-method:
public MultipartFormDataContent SendFileToChannel()
{
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(GetFile.ReadFile());
requestContent.Add(new StringContent(token), "token");
requestContent.Add(fileContent, "file", Path.GetFileName(GetFile.path));
return requestContent;
}
there is no 'channel' in this method because I don't want to publish it yet.
Then I set "public_url_shared": true and get the public URL(with another method).
In the response evreything seems to be okay, shared is set to true and I get a permalink_public-value which I pass on to post a message containing this file but...
Now I should be able to post a message while using the permalink_url I get from the second method. And this works with images. But it doesn't work with files.
I allways get the error response "no_file_data".
Here is my method for this:
public MultipartFormDataContent SendMessageWithFile(SlackFileResponse resp)
{
var requestContent = new MultipartFormDataContent();
requestContent.Add(new StringContent(token), "token");
requestContent.Add(new StringContent(channel), "channel");
requestContent.Add(new StringContent(text), "text");
requestContent.Add(new StringContent("[{ \"fallback\":\"Anhang\", \"text\":\"\", \"\":\"" + resp.permalink_public + "\"}]"), "attachments");
return requestContent;
}
Am I doing something wrong here? Because via the RTM-Slack one can easily just drag&drop a file in there and add a message to it. So it has to be possible via the SlackAPI ,too. Right?
Here is why this approach does not work:
Slack threats images differently from other files. Images are the only type of file that you can include in a message attachment via URL. For that we have the properties image_url (and thumb_url) for attachments.
Check out this page for a list of all available attachment properties.
If you want to post any other file in a Slack channel and be able to comment it you need to upload it via files.upload and share it immediately. That is important, because it is currently not possible via the official API to share a previously uploaded file in a channel at a later point.
To include a comment with your file upload just set the initial_comment property in your API call.
Example:
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(GetFile.ReadFile());
requestContent.Add(new StringContent(token), "token");
requestContent.Add(new StringContent("my_channel"), "channels");
requestContent.Add(new StringContent("Check out this amazing new file"), "initial_comment");
requestContent.Add(fileContent, "file", Path.GetFileName(GetFile.path));
I am uploading a file with C# code on php server. But facing some issues.
First I was using a WebClient Object to upload file by calling UploadFile() method, and uploading string to by calling UploadString() method by following code:
String StoreID = "First Store";
WebClient Client = new WebClient();
String s = Client.UploadString("http://localhost/upload.php", "POST", StoreID);
Client.Headers.Add("Content-Type","binary/octet-stream");
byte[] result = Client.UploadFile("http://localhost/upload.php", "POST", "C:\\aaaa.jpg");
s = s + System.Text.Encoding.UTF8.GetString(result,0,result.Length);
Issue is that I am requesting two times so string and file is not being send at same time. I am receiving either String or File. But I need both at same time. I don't want to use UploadData() becuase it will use byte codes and I have know I idea how to extract it in php.
Let that string is folder name, i have to send string and file, so that file could save at specified folder at php server.
I studied there may be a solution with WebRequest and WebResponse object. But dont know how to send request using WebResponse by C# and get it at PHP.
Any Suggestions!!!!
Try this :
WebClient web = new WebClient();
try{
web.UploadFile("http://" + ip + "/test.php", StoreID);
}
catch(Exception e)
{
MessageBox.Show("Upload failed");
}
Now you can access the file from the PHP file.
<?php
//check whether the folder the exists
if(!(file_exists('C:/Users/dhanu-sdu/Desktop/test')))
{
//create the folder
mkdir('C:/Users/ComputerName/Desktop/test');
//give permission to the folder
chmod('C:/Users/ComputerName/Desktop/test', 0777);
}
//check whether the file exists
if (file_exists('C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
//move the file into the new folder
move_uploaded_file($_FILES["file"]["tmp_name"],'C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]);
}
?>
Also, you can download data from a PHP server and display it in a C# web browser by using the following codes :
WebClient web = new WebClient();
try{
byte[] response = web.DownloadData("http://" + ip +"/test.php");
webBrowser1.DocumentText = System.Text.ASCIIEncoding.ASCII.GetString(response);
}
catch(Exception e)
{
MessageBox.Show("Download failed");
}
You can create a webservice with php that accepts a file. Then publish that webservice, and add it to you c# references, then just call teh method from within your c# code that accepts the file, and vualá!
How to create SOAP with php link