C# file uploading with a string using on PHP server - c#

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

Related

Convert Curl command with WAV file to Unity web request

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");

Get reply from remote server using C# and PHP

I'm trying to get data from a remote server using C#. I tried using a simple script to see if "it works", but I'm not getting a response. The same script works on a local server, so I'd like to know how I can do it.
This is my C# code:
IEnumerator Sayhi()
{
WWWForm sendInfo = new WWWForm();
sendInfo.AddField("function", function);
WWW www = new WWW(bl_LoginDataBase.Instance.GetUrl(bl_LoginDataBase.URLType.CallFunction), sendInfo);
yield return www;
Debug.Log(www.text);
}
And the PHP code:
<?php
echo "Hi";
I expected the Debug.Log(www.text); to print Hi, which it does if I use a local machine (http://192.168.0.whatever), but the remote server (http://whatever.example.com) doesn't return anything. I tried making the php fail so it returns an error, make a database and return some values from there, but nothing. I'd like to point out it does work on a local server, and works as intended.
What am I doing wrong?
Edit: By the way, if I access http://www.whatever.example.com/Function.php via browser, it shows the echo result.
C# has built in classes and methods to help you perform such tasks.You can use the WebClient class to connect to web servers (using GET or POST) and even send form values to it easily. See below:
string url ="http://www.whatever.example.com/Function.php";
var reqparam = new System.Collections.Specialized.NameValueCollection();
reqparam.Add("name", "John Doe");
try
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
byte[] responsebytes = client.UploadValues(url, "POST", parameters);
string output = System.Text.Encoding.UTF8.GetString(responsebytes);
}
}
catch (Exception x)
{
//an error occured
}
The variable output will contain the response you want "Hi".

How can I send a File over a REST API?

I am trying to send a file to a server over a REST API. The file could potentially be of any type, though it can be limited in size and type to things that can be sent as email attachments.
I think my approach will be to send the file as a binary stream, and then save that back into a file when it arrives at the server. Is there a built in way to do this in .Net or will I need to manually turn the file contents into a data stream and send that?
For clarity, I have control over both the client and server code, so I am not restricted to any particular approach.
I'd recommend you look into RestSharp
http://restsharp.org/
The RestSharp library has methods for posting files to a REST service. (RestRequst.AddFile()). I believe on the server-side this will translate into an encoded string into the body, with the content-type in the header specifying the file type.
I've also seen it done by converting a stream to a base-64 string, and transferring that as one of the properties of the serialized json/xml object. Especially if you can set size limits and want to include file meta-data in the request as part of the same object, this works really well.
It really depends how large your files are though. If they are very large, you need to consider streaming, of which the nuances of that is covered in this SO post pretty thoroughly: How do streaming resources fit within the RESTful paradigm?
You could send it as a POST request to the server, passing file as a FormParam.
#POST
#Path("/upload")
//#Consumes(MediaType.MULTIPART_FORM_DATA)
#Consumes("application/x-www-form-urlencoded")
public Response uploadFile( #FormParam("uploadFile") String script, #HeaderParam("X-Auth-Token") String STtoken, #Context HttpHeaders hh) {
// local variables
String uploadFilePath = null;
InputStream fileInputStream = new ByteArrayInputStream(script.getBytes(StandardCharsets.UTF_8));
//System.out.println(script); //debugging
try {
uploadFilePath = writeToFileServer(fileInputStream, SCRIPT_FILENAME);
}
catch(IOException ioe){
ioe.printStackTrace();
}
return Response.ok("File successfully uploaded at " + uploadFilePath + "\n").build();
}
private String writeToFileServer(InputStream inputStream, String fileName) throws IOException {
OutputStream outputStream = null;
String qualifiedUploadFilePath = SIMULATION_RESULTS_PATH + fileName;
try {
outputStream = new FileOutputStream(new File(qualifiedUploadFilePath));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.flush();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally{
//release resource, if any
outputStream.close();
}
return qualifiedUploadFilePath;
}
Building on to #MutantNinjaCodeMonkey's suggestion of RestSharp. My use case was posting webform data from jquery's $.ajax method into a web api controller. The restful API service required the uploaded file to be added to the request Body. The default restsharp method of AddFile mentioned above caused an error of The request was aborted: The request was canceled. The following initialization worked:
// Stream comes from web api's HttpPostedFile.InputStream
(HttpContext.Current.Request.Files["fileUploadNameFromAjaxData"].InputStream)
using (var ms = new MemoryStream())
{
fileUploadStream.CopyTo(ms);
photoBytes = ms.ToArray();
}
var request = new RestRequest(Method.PUT)
{
AlwaysMultipartFormData = true,
Files = { FileParameter.Create("file", photoBytes, "file") }
};
Detect the file/s being transported with the request.
Decide on a path where the file will be uploaded (and make sure CHMOD 777 exists for this directory)
Accept the client connect
Use ready library for the actual upload
Review the following discussion:
REST file upload with HttpRequestMessage or Stream?
First, you should login to the server and get an access token.
Next, you should convert your file to stream and post the stream:
private void UploadFile(FileStream stream, string fileName)
{
string apiUrl = "http://example.com/api";
var formContent = new MultipartFormDataContent
{
{new StringContent(fileName),"FileName"},
{new StreamContent(stream),"formFile",fileName},
};
using HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", accessToken);
var response = httpClient.PostAsync(#$"{apiUrl}/FileUpload/save", formContent);
var result = response.Result.Content.ReadAsStringAsync().Result;
}
In this example, we upload the file to http://example.com/api/FileUpload/save and the controller has the following method in its FileUpload controller:
[HttpPost("Save")]
public ActionResult Save([FromForm] FileContent fileContent)
{
// ...
}
public class FileContent
{
public string FileName { get; set; }
public IFormFile formFile { get; set; }
}

upload file from window application to Remote Web Server

string filePath = "C:\\test\\564.flv";
try
{
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential(uName, password);
Uri addy = new Uri("\\\\192.168.1.28\\Files\\test.flv");
client.Credentials = nc;
byte[] arrReturn = client.UploadFile(addy, filePath);
Console.WriteLine(arrReturn.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
i am get this error "The remote server returned an error: (405) Method Not Allowed." what should i doo ??
WebClient uses POST method to upload a file in an HTTP server or uses STOR command to upload a file in an FTP server. It can't upload files in a network folder.
I do not believe the UploadFile() method can have a UNC address for the URI. See the documentation for the method: http://msdn.microsoft.com/en-us/library/ms144229.aspx. It needs to either be an FTP site or an HTTP site.

Upload a file referenced via URL

I have url that point to image for example :
http://cg009.k12.sd.us/images/smilefacemoving.gif
instead of user will insert file i want to bind this file(image) to the c# fileupload control .
so the fileupload object will hold this file(image).
Just have a Textbox on your page to let them enter a URL and then do this when the form is submitted...
string url = YOUR_TEXTBOX.Text();
Uri uri;
try {
uri = new Uri(url);
}
catch (UriFormatException ex) {
// Error
throw ex;
}
byte[] file;
using (System.Net.WebClient client = new System.Net.WebClient()) {
file = client.DownloadData(uri);
}
// now you have the file
Watch out for uploaded viruses :)
I'm honestly not sure what you're asking. Are you asking how you can upload a file referenced via a URL to your own server utilizing the fileupload control?

Categories

Resources