如何上传文字和使用Httpwebrequest(Multipart / Form-Data)到Web服务器(运行I Php)的文件? [英] How To Upload Text & Files Using Httpwebrequest (Multipart/Form-Data) To A Web Server (Running I Php) ?

查看:60
本文介绍了如何上传文字和使用Httpwebrequest(Multipart / Form-Data)到Web服务器(运行I Php)的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上传文字&从c#中的桌面应用程序到Web服务器(运行i php)的文件,



所以我试试这段代码:



在C#中:



  string  URL = < span class =code-string>  http://localhost/TestUploadFile.php; 
string boundary = ---- ------------------------ + DateTime.Now.Ticks.ToString( x);
WebRequest webRequest = WebRequest.Create(URL);
webRequest.Method = POST;
webRequest.ContentType = multipart / form-data; boundary = + boundary;

流postDataStream = new MemoryStream();

// 添加表单数据
string formDataHeaderTemplate = Environment.NewLine + - + boundary + Environment.NewLine + Content-Disposition:form-data; name = \{0} \; + Environment.NewLine + Environment.NewLine + {1};
byte [] formItemBytes = Encoding.UTF8.GetBytes( string .Format(formDataHeaderTemplate,< span class =code-string> value valueTest));
postDataStream.Write(formItemBytes, 0 ,formItemBytes.Length);

// 添加文件数据

< span class =code-keyword> string
FilePath = @ C:\ test \ ;

string [] files = Directory.GetFiles(FilePath);

for int i = 0 ; i < files.Length; i ++)
{
FileInfo fileInfo = new FileInfo(files [i]);
string fileHeaderTemplate = Environment.NewLine + - + boundary + Environment.NewLine + Content-Disposition:form-data; name = \\ \\{0} \; filename = \{1} \ + Environment.NewLine + Content-Type:application / octet-stream + Environment.NewLine + Environment.NewLine;
byte [] fileHeaderBytes = Encoding.UTF8.GetBytes( string .Format(fileHeaderTemplate,< span class =code-string>
UploadFile,fileInfo.FullName));
postDataStream.Write(fileHeaderBytes, 0 ,fileHeaderBytes.Length);

FileStream fileStream = fileInfo.OpenRead();

byte [] bufferFiles = new byte [ 1024 ];

int bytesRead = 0 ;

while ((bytesRead = fileStream.Read(bufferFiles, 0 ,bufferFiles .Length))!= 0
{
postDataStream.Write(buffer, 0 ,bytesRead);
}

fileStream.Close();
}

byte [] endBoundaryBytes = Encoding.UTF8.GetBytes( - + boundary + - );

postDataStream.Write(endBoundaryBytes, 0 ,endBoundaryBytes.Length);

webRequest.ContentLength = postDataStream.Length;

Stream reqStream = webRequest.GetRequestStream();

postDataStream.Position = 0 ;

byte [] buffer = new byte [ 1024 ];

int bytesRead = 0 ;

while ((bytesRead = postDataStream.Read(buffer, 0 ,缓冲区.Length))!= 0
{
reqStream.Write(buffer, 0 ,bytesRead);
}

postDataStream.Close();
reqStream.Close();

StreamReader sr = new StreamReader(webRequest.GetResponse()。GetResponseStream());
string Result = sr.ReadToEnd();

MessageBox.Show(Result);





在我的WebApplication中(在php中)



 <?php  

$ uploaddir = ' upload /'; // 相对上传数据文件的位置

if(isset($ _ FILES) [' file'] [' < span class =code-string> tmp_name'])){
if (is_uploaded_file($ _ FILES [' file'] [' tmp_name'])){

$ uploadfile = $ uploaddir 。 basename($ _ FILES [' file'] [' name']);
echo ' 文件' 。 $ _FILES [' file'] [' name']。 ' 已成功上传';
if (move_uploaded_file($ _ FILES [' file'] [' tmp_name'],$ uploadfile)){
echo 文件有效,并已成功移动< /跨度>;
}
else {
print_r($ _ FILES);
}
}
其他 {
echo < span class =code-string>
上传失败!!!;
}
}

if(isset($ _ POST [' 值'])){
echo $ _POST [' ];
}
其他 {
echo ' not value';
}





MessageBox返回上传文件的失败和表单数据的valueTest(成功表单数据)



我认为问题出在Content-Type:application / octet-stream !!!我想上传所有类型的文件(.txt,.pdf,.msg,...)



我无法理解内容类型的工作方式和我不知道边界的重要性!!!



你能帮我吗?

解决方案

uploaddir = ' upload /'; // 相对上传数据文件的位置

if(isset(


_FILES [' file'] [' tmp_name'])){
if (is_uploaded_file (


_FILES [' file'] [' tmp_name'])){


I want to upload text & files from a desktop application in c# to a web server (running i php),

So I try this code :

In C# :

string URL = "http://localhost/TestUploadFile.php";
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
WebRequest webRequest = WebRequest.Create(URL);
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

Stream postDataStream = new MemoryStream();

//adding form data
string formDataHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine + "Content-Disposition: form-data; name=\"{0}\";" + Environment.NewLine + Environment.NewLine + "{1}";
byte[] formItemBytes = Encoding.UTF8.GetBytes(string.Format(formDataHeaderTemplate, "value", "valueTest"));
postDataStream.Write(formItemBytes, 0, formItemBytes.Length);

//adding file data

string FilePath = @"C:\test\";

string[] files = Directory.GetFiles(FilePath);

for(int i = 0; i < files.Length; i++)
{
    FileInfo fileInfo = new FileInfo(files[i]);
    string fileHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine + "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + Environment.NewLine + "Content-Type: application/octet-stream" + Environment.NewLine + Environment.NewLine;
    byte[] fileHeaderBytes = Encoding.UTF8.GetBytes(string.Format(fileHeaderTemplate, "UploadFile", fileInfo.FullName));
    postDataStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);

    FileStream fileStream = fileInfo.OpenRead();

    byte[] bufferFiles = new byte[1024];

    int bytesRead = 0;

    while ((bytesRead = fileStream.Read(bufferFiles, 0, bufferFiles.Length)) != 0)
    {
        postDataStream.Write(buffer, 0, bytesRead);
    }

    fileStream.Close();
}

byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--");

postDataStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);

webRequest.ContentLength = postDataStream.Length;

Stream reqStream = webRequest.GetRequestStream();

postDataStream.Position = 0;

byte[] buffer = new byte[1024];

int bytesRead = 0;

while ((bytesRead = postDataStream.Read(buffer, 0, buffer.Length)) != 0)
{
    reqStream.Write(buffer, 0, bytesRead);
}

postDataStream.Close();
reqStream.Close();

StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream());
string Result = sr.ReadToEnd();

MessageBox.Show(Result);



In my WebApplication (in php)

<?php

$uploaddir = 'upload/'; // Relative Upload Location of data file

if(isset($_FILES['file']['tmp_name'])) {
    if (is_uploaded_file($_FILES['file']['tmp_name'])) {

        $uploadfile = $uploaddir . basename($_FILES['file']['name']);
        echo 'File '. $_FILES['file']['name']. ' uploaded successfully';
        if ( move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile) ) {
        echo "File is valid, and was successfully moved ";
    }
    else {
        print_r($_FILES);
    }
}
else {
    echo "Upload Failed !!!";
}
}

if(isset($_POST['value'])) {
echo $_POST['value'];
}
else {
echo 'not value';
}



The MessageBox return "Failed" for upload files and the valueTest for form data (success for form data)

I think the problem is in the Content-Type: application/octet-stream !!! I want to upload all type of file (.txt, .pdf, .msg, ...)

I can't understand how to Content-Type work and I do not know the importance of boundary !!!

Can you help me please ?

解决方案

uploaddir = 'upload/'; // Relative Upload Location of data file if(isset(


_FILES['file']['tmp_name'])) { if (is_uploaded_file(


_FILES['file']['tmp_name'])) {


这篇关于如何上传文字和使用Httpwebrequest(Multipart / Form-Data)到Web服务器(运行I Php)的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆