Viewed   108 times

I want to upload file to a host by using WebClient class. I also want to pass some values which should be displayed in the $_POST array on the server part (PHP). I want to do it by one connect

I've used code bellow

using (WebClient wc = new WebClient())
{
    wc.Encoding = Encoding.UTF8;
    NameValueCollection values = new NameValueCollection();
    values.Add("client", "VIP");
    values.Add("name", "John Doe"); 
    wc.QueryString = values; // this displayes in $_GET
    byte[] ans= wc.UploadFile(address, dumpPath);
}

If i've used QueryString property, the values displayed in $_GET array.But i want to send it by post method

 Answers

4

There's nothing built-in that allows you to do that. I have blogged about an extension that you could use. Here are the relevant classes:

public class UploadFile
{
    public UploadFile()
    {
        ContentType = "application/octet-stream";
    }
    public string Name { get; set; }
    public string Filename { get; set; }
    public string ContentType { get; set; }
    public Stream Stream { get; set; }
}

public byte[] UploadFiles(string address, IEnumerable<UploadFile> files, NameValueCollection values)
{
    var request = WebRequest.Create(address);
    request.Method = "POST";
    var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
    request.ContentType = "multipart/form-data; boundary=" + boundary;
    boundary = "--" + boundary;

    using (var requestStream = request.GetRequestStream())
    {
        // Write the values
        foreach (string name in values.Keys)
        {
            var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
            requestStream.Write(buffer, 0, buffer.Length);
            buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name="{0}"{1}{1}", name, Environment.NewLine));
            requestStream.Write(buffer, 0, buffer.Length);
            buffer = Encoding.UTF8.GetBytes(values[name] + Environment.NewLine);
            requestStream.Write(buffer, 0, buffer.Length);
        }

        // Write the files
        foreach (var file in files)
        {
            var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
            requestStream.Write(buffer, 0, buffer.Length);
            buffer = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name="{0}"; filename="{1}"{2}", file.Name, file.Filename, Environment.NewLine));
            requestStream.Write(buffer, 0, buffer.Length);
            buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: {0}{1}{1}", file.ContentType, Environment.NewLine));
            requestStream.Write(buffer, 0, buffer.Length);
            file.Stream.CopyTo(requestStream);
            buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
            requestStream.Write(buffer, 0, buffer.Length);
        }

        var boundaryBuffer = Encoding.ASCII.GetBytes(boundary + "--");
        requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
    }

    using (var response = request.GetResponse())
    using (var responseStream = response.GetResponseStream())
    using (var stream = new MemoryStream())
    {
        responseStream.CopyTo(stream);
        return stream.ToArray();
    }
}

and now you could use it in your application:

using (var stream = File.Open(dumpPath, FileMode.Open))
{
    var files = new[] 
    {
        new UploadFile
        {
            Name = "file",
            Filename = Path.GetFileName(dumpPath),
            ContentType = "text/plain",
            Stream = stream
        }
    };

    var values = new NameValueCollection
    {
        { "client", "VIP" },
        { "name", "John Doe" },
    };

    byte[] result = UploadFiles(address, files, values);
}

Now in your PHP script you could use the $_POST["client"], $_POST["name"] and $_FILES["file"].

Wednesday, September 21, 2022
5

Some providers does not allow you change certain values in running time. Instead of this, try to either change it in the real php.ini file or use an .htaccess (For Apache web servers) where you can add your configuration. You can find more information in the PHP.net article about this subject: How to change configuration settings.

Based on your story, example .htaccess

<IfModule mod_php5.c>
php_value upload_max_filesize 100000000
php_value post_max_size 110000000
php_value memory_limit 120000000
php_value max_input_time 20
</IfModule>
Wednesday, December 14, 2022
 
msc
 
msc
1

I have tried the same code and it works for me. I have made some changes for you.

<form method="POST" enctype="multipart/form-data">
    <label for="">Upload Your Cv</label><input type="file" name="file">
    <input type="submit" name="upload" value="upload">
</form>

After that you don't need to redirect the page; instead you can use this, below the </form>

if(isset($_REQUEST["upload"]))
{
if (isset($_FILES['file'])) {
        $file   = $_FILES['file'];
        // print_r($file);  just checking File properties

        // File Properties
        $file_name  = $file['name'];
        $file_tmp   = $file['tmp_name'];
        $file_size  = $file['size'];
        $file_error = $file['error'];

        // Working With File Extension
        $file_ext   = explode('.', $file_name);
        $file_fname = explode('.', $file_name);

        $file_fname = strtolower(current($file_fname));
        $file_ext   = strtolower(end($file_ext));
        $allowed    = array('txt','pdf','doc','ods');


        if (in_array($file_ext,$allowed)) {
            //print_r($_FILES);


            if ($file_error === 0) {
                if ($file_size <= 5000000) {
                        $file_name_new     =  $file_fname . uniqid('',true) . '.' . $file_ext;
                        $file_name_new    =  uniqid('',true) . '.' . $file_ext;
                        $file_destination =  'upload/' . $file_name_new;
                        // echo $file_destination;
                        if (move_uploaded_file($file_tmp, $file_destination)) {
                                echo "Cv uploaded";
                        }
                        else
                        {
                            echo "some error in uploading file".mysql_error();
                        }
//                        
                }
                else
                {
                    echo "size must bne less then 5MB";
                }
            }

        }
        else
        {
            echo "invalid file";
        }
}
}

Note that the upload folder must be in the same directory as where you store the file.

Sunday, October 9, 2022
 
3

You have to make sure the port you are connecting to is port 443 instead of port 80.

Example of explicitly setting the port to be used in the URL:

var request = (HttpWebRequest) WebRequest.Create("https://example.com:443/");
request.Method = "GET";
request.UserAgent = "example/1.0";
request.Accept = "*/*";
request.Host = "example.com";

var resp = (HttpWebResponse) request.GetResponse();
Sunday, October 23, 2022
3

I ended up keeping the rawData[] buffer and specifying contentLength in the request:

webClient.post()
         .uri(uri)
         .contentType(MediaType.APPLICATION_OCTET_STREAM)
         .contentLength(bytes.length)
         .bodyValue(bytes)
         .exchange()
         .block(Duration.ofSeconds(30));

For very large files I did chunked uploads - for example 1Mb chunks of a file might look like:

POST: https://sharepoint.acme.com:443/sharepoint-site/_api/web/GetFileByServerRelativeUrl(@f)/StartUpload(uploadId=guid'680f93eb-8c6a-443d-87ad-1e1b324ea678')?@f='/sharepoint-site/folderA/subFolderB/etc/example.file'
POST: https://sharepoint.acme.com:443/sharepoint-site/_api/web/GetFileByServerRelativeUrl(@f)/ContinueUpload(uploadId=guid'680f93eb-8c6a-443d-87ad-1e1b324ea678',fileOffset=1048576)?@f='/sharepoint-site/folderA/subFolderB/etc/example.file'
POST: https://sharepoint.acme.com:443/sharepoint-site/_api/web/GetFileByServerRelativeUrl(@f)/ContinueUpload(uploadId=guid'680f93eb-8c6a-443d-87ad-1e1b324ea678',fileOffset=2097152)?@f='/sharepoint-site/folderA/subFolderB/etc/example.file'
POST: https://sharepoint.acme.com:443/sharepoint-site/_api/web/GetFileByServerRelativeUrl(@f)/ContinueUpload(uploadId=guid'680f93eb-8c6a-443d-87ad-1e1b324ea678',fileOffset=3145728)?@f='/sharepoint-site/folderA/subFolderB/etc/example.file'
POST: https://sharepoint.acme.com:443/sharepoint-site/_api/web/GetFileByServerRelativeUrl(@f)/ContinueUpload(uploadId=guid'680f93eb-8c6a-443d-87ad-1e1b324ea678',fileOffset=4194304)?@f='/sharepoint-site/folderA/subFolderB/etc/example.file'
POST: https://sharepoint.acme.com:443/sharepoint-site/_api/web/GetFileByServerRelativeUrl(@f)/ContinueUpload(uploadId=guid'680f93eb-8c6a-443d-87ad-1e1b324ea678',fileOffset=5242880)?@f='/sharepoint-site/folderA/subFolderB/etc/example.file'
POST: https://sharepoint.acme.com:443/sharepoint-site/_api/web/GetFileByServerRelativeUrl(@f)/FinishUpload(uploadId=guid'680f93eb-8c6a-443d-87ad-1e1b324ea678',fileOffset=6291456)?@f='/sharepoint-site/folderA/subFolderB/etc/example.file'

Driven by working on the raw bytes:

final UUID id = UUID.randomUUID();
int offset = 0;
while (offset < bytesTotal) {
    final URI uri;
    if (offset == 0) {
        uri = createStartUri(id, path, filename);
    } else if (offset < bytesTotal - CHUNK_SIZE) {
        uri = createContinueUri(id, offset, path, filename);
    } else {
        uri = createFinishUri(id, offset, path, filename);
    }
    final byte[] bytes = ArrayUtils.subarray(fileDataBytes, offset, offset + CHUNK_SIZE);

    webClient.post().uri(uri).contentType(MediaType.APPLICATION_OCTET_STREAM).contentLength(bytes.length)
            .bodyValue(bytes).exchange().block(Duration.ofSeconds(30));
    
    offset += CHUNK_SIZE;
}
Thursday, December 22, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :