最近要写一个webapi接口,用于接受上传文件操作。直接上代码
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/UploadFile", ResponseFormat = WebMessageFormat.Json)]
public string UploadFile()
{
string result = string.Empty;
try
{
//核心部分
string fileName = HttpContext.Current.Request.Files[0].FileName;
Stream stream = HttpContext.Current.Request.Files[0].InputStream;
string uploadFolder = "上传文件夹位置";
string savePath = System.IO.Path.Combine(uploadFolder, fileName);
FileStream fsWrite = new FileStream(savePath, FileMode.Create);
byte[] bytes = new byte[1024 * 4];
int total = 0;
int size = 0;
do
{
//注意第二个参数是在buffer中的偏移量,不是在文件中的偏移量
size = stream.Read(bytes, 0, bytes.Length);
fsWrite.Write(bytes, 0, size);
total += size;
} while (size > 0);
fsWrite.Close();
result = "true";
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
这里放一下我在POST得测试