unity
using UnityEngine;
using System.Collections;
public class SavePicture : MonoBehaviour
{
string url = "http://localhost:8888/upload_file.php";
string path;
public Material image;
void Start()
{
path = Application.dataPath + "/wukuaTurret.jpg";
}
void OnGUI()
{
if (GUI.Button(new Rect(100, 100, 100, 100), "SavePic"))
{
Debug.Log(path);
StartCoroutine(getTexture2d());
}
}
IEnumerator getTexture2d()
{
yield return new WaitForEndOfFrame();
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0, false);
tex.Apply();
byte[] bytes = tex.EncodeToPNG();
WWWForm form = new WWWForm();
//form.AddField("Name", "pic1");
form.AddBinaryData("file", bytes);
//form.AddBinaryData("file", bytes, "hh.jpg", "image/png");
WWW www = new WWW(url, form);
StartCoroutine(PostData(www));
Destroy(tex);
System.IO.File.WriteAllBytes(path, bytes);
}
IEnumerator PostData(WWW www)
{
yield return www;
Debug.Log("ok");
Debug.Log(www.text);
}
}
文件目录:
php
<?php
$fileName =$_FILES["file"]["name"];
if ($_FILES["file"]["error"] > 0)
{
echo "错误:: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "上传文件名: " . $_FILES["file"]["name"] . "<br>";
echo "文件类型: " . $_FILES["file"]["type"] . "<br>";
echo "文件大小: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "文件临时存储的位置: " . $_FILES["file"]["tmp_name"] . "<br>";
// 判断当期目录下的 upload 目录是否存在该文件
// 如果没有 upload 目录,你需要创建它,upload 目录权限为 777
if (file_exists("upload/" . $fileName))
{
echo $fileName . " 文件已经存在。 ". "<br>";
if (!unlink(("upload/" .$fileName))) {
echo "Error deleting $fileName". "<br>";
}else{
echo ("Deleted $fileName"). "<br>";
echo "开始存储文件". "<br>";
// 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "文件存储在: " . "upload/" . $_FILES["file"]["name"]. "<br>";
}
}
else
{
// 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "文件存储在: " . "upload/" . $_FILES["file"]["name"]. "<br>";
}
}
?>
index.html
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
其他:
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using RestSharp;
using System.Collections.Specialized;
using System.IO;
using System;
using System.Net;
using System.Linq;
using System.Threading;
using System.Text;
public class httpupload : MonoBehaviour {
static Stream FileToStream(string fileName)
{
// 打开文件
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
// 读取文件的 byte[]
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
// 把 byte[] 转换成 Stream
Stream stream = new MemoryStream(bytes);
return stream;
}
static string Upload(string url, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
Stream postStream = new MemoryStream();
#region 处理Form表单文件上传
//通过表单上传文件
string boundary = "----" + DateTime.Now.Ticks.ToString("x");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"name\"; filename=\"{1}\"\r\nContent-Type: image/jpeg\r\n\r\n";
try
{
//准备文件流
using (var fileStream = FileToStream(fileName))
{
var formdata = string.Format(formdataTemplate, "", System.IO.Path.GetFileName(fileName) /*Path.GetFileName(fileName)*/);
var formdataBytes = Encoding.UTF8.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要换行
postStream.Write(formdataBytes, 0, formdataBytes.Length);
//写入文件
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
postStream.Write(buffer, 0, bytesRead);
}
}
}
catch (Exception ex)
{
throw ex;
}
//结尾
var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
postStream.Write(footer, 0, footer.Length);
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
#endregion
request.ContentLength = postStream != null ? postStream.Length : 0;
request.Accept = "*/*";
//request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
#region 输入二进制流
if (postStream != null)
{
postStream.Position = 0;
//直接写入流
Stream requestStream = request.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
postStream.Close();//关闭文件访问
}
#endregion
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
{
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
}
void Start () {
string url = "http://********/api/";
string filePath = "D:\\2.jpg";
string result = Upload(url, filePath);
Debug.Log(result);
Application.OpenURL(result);
}
// Update is called once per frame
void Update () {
}
}