Php 文件上传 ,服务器端代码和客户端代码


=============================客户端==========================================
<html>
<head>
<title>File Upload Form</title>
</head>
<body>
This form allows you to upload a file to the server.<br>
<form enctype="multipart/form-data" method="post" action="test.php">
       Send this file: <input name="userfile" type="file" /><br />
       <input type="submit" value="Send File" />
</form>
</body>
</html>

=====================================================================


=================================服务端====================================

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
<html>
       <head>
               <title>Example</title>
       </head>
       <body>
             <?php          
             print "Received {$_FILES['userfile']['name']} - its size is {$_FILES['userfile']['size']}";
                                 
if ( move_uploaded_file($_FILES["userfile"]["tmp_name"], "C:\Windows\Temp\a.txt"))
           {   print '<p> The file has been successfully uploaded </p>';
             }
else
           {
               switch ($_FILES['userfile'] ['error'])
                 {   case 1:
                                     print '<p> The file is bigger than this PHP installation allows</p>';
                                     break;
                       case 2:
                                     print '<p> The file is bigger than this form allows</p>';
                                     break;
                       case 3:
                                     print '<p> Only part of the file was uploaded</p>';
                                     break;
                       case 4:
                                     print '<p> No file was uploaded</p>';
                                     break;
                 }
             }
             print_r($_FILES);
             print '<p> Tsss </p>';

?>
       </body>
</html>
===============================================================================

如果是在Windows NT确保上传的目录是给Everyone的,这样才有权限上传。

php.ini设置,

default_socket_timeout = 60
;upload_tmp_dir="C:\Windows\Temp"
upload_tmp_dir="D:\TTT"
session.save_path="C:\Windows\Temp"
error_log="C:\Windows\temp\php-errors.log"

===============================客户端C# 代码==================================================

using System;
using System.Web;
using System.Collections.Specialized;
using System.Text;
using System.Net;
using System.IO;
namespace UploadFileEx
{
       /// <summary>
       /// Summary description for Class1.
       /// </summary>
       class Class1
       {

              public static string UploadFileEx(       string uploadfile, string url,
                     string fileFormName, string contenttype,NameValueCollection querystring,
                     CookieContainer cookies)
              {
                     if( (fileFormName== null) ||
                            (fileFormName.Length ==0))
                     {
                            fileFormName = "file";
                     }

                     if( (contenttype== null) ||
                            (contenttype.Length ==0))
                     {
                            contenttype = "application/octet-stream";
                     }


                     string postdata;
                     postdata = "?";
                     if (querystring!=null)
                     {
                            foreach(string key in querystring.Keys)
                            {
                                   postdata+= key +"=" + querystring.Get(key)+"&";
                            }
                     }
                     //Uri uri = new Uri(url+postdata);
                       Uri uri = new Uri(url);

                     string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                     HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
                     webrequest.CookieContainer = cookies;
                     webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
                     webrequest.Method = "POST";


                     // Build up the post message header
                     StringBuilder sb = new StringBuilder();
                     sb.Append("--");
                     sb.Append(boundary);
                     sb.Append("\r\n");
                     sb.Append("Content-Disposition: form-data; name=\"");
                     sb.Append(fileFormName);
                     sb.Append("\"; filename=\"");
                     sb.Append(Path.GetFileName(uploadfile));
                     sb.Append("\"");
                     sb.Append("\r\n");
                     sb.Append("Content-Type: ");
                     sb.Append(contenttype);
                     sb.Append("\r\n");
                     sb.Append("\r\n");                   

                     string postHeader = sb.ToString();
                     byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

                     // Build the trailing boundary string as a byte array
                     // ensuring the boundary appears on a line by itself
                     byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

                     FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
                     long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
                     webrequest.ContentLength = length;

                     Stream requestStream = webrequest.GetRequestStream();

                     // Write out our post header
                     requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

                     // Write out the file contents
                     byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
                     int bytesRead = 0;
                     while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
                            requestStream.Write(buffer, 0, bytesRead);
 
                     // Write out the trailing boundary
                     requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                     WebResponse responce = webrequest.GetResponse();
                     Stream s = responce.GetResponseStream();
                     StreamReader sr = new StreamReader(s);

                     return sr.ReadToEnd();
              }
              /// <summary>
              /// The main entry point for the application.
              /// </summary>
              [STAThread]
              static void Main(string[] args)
              {
                     CookieContainer cookies = new CookieContainer();
                     //add or use cookies

                     NameValueCollection querystring = new NameValueCollection();
                   
                     // simulate this form
                     //<form action ="http://localhost/test.php" method = POST>
                     //<input type = text name = uname>
                     //<input type = password name =passwd>
                     //<input type = FILE name = uploadfile>
                     //<input type=submit>


                     querystring["uname"]="uname";
                     querystring["passwd"]="snake3";

                     string uploadfile;// set to file to upload

                     uploadfile = "c:\\test.jpg";
                   

                     //everything except upload file and url can be left blank if needed

                     UploadFileEx(uploadfile,"http://localhost/test.php","userfile", "image/pjpeg",
                            querystring,cookies);


                          
              }
       }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值