wcf rest を使用したファイル アップロードの例を次に示します。
[ServiceContract]
interface IUploader
{
[WebInvoke(UriTemplate = "FileUpload?public_id={public_id}&tags={tags}",
Method = "POST",
ResponseFormat = WebMessageFormat.Json)]
UploadImageResult UploadImage(Stream fileContents, string public_id, string tags);
}
public class Uploader : IUploader
{
public UploadImageResult UploadImage(Stream fileContents, string public_id, string tags)
{
try
{
byte[] buffer = new byte[32768];
FileStream fs = File.Create(Path.Combine(rootFolderPath, @"test\test.jpg"));
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileContents.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
fs.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
fs.Close();
}
catch(Exception ex)
{
...
}
}
}
C# を使用して呼び出すには
// Create the REST URL.
string requestUrl = @"http://localhost:2949/fileupload?public_id=id&tags=tags";
//file to upload make sure it exist
string filename = @"C:\temp\ImageUploaderService\vega.jpg";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
//request.ContentType = "text/plain";
request.ContentType = "application/json; charset=utf-8";
byte[] fileToSend = File.ReadAllBytes(filename);
request.ContentLength = fileToSend.Length;
using (Stream requestStream = request.GetRequestStream())
{
// Send the file as body request.
requestStream.Write(fileToSend, 0, fileToSend.Length);
requestStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
dynamic testObj = Newtonsoft.Json.JsonConvert.DeserializeObject(text);
Console.WriteLine(string.Format("response url is {0}", testObj.url));
}
質問 2、例のように、リクエストの URL にキーと値のペアを使用してデータを追加できます。
それが役立つことを願っています。