【发布时间】:2015-12-10 04:00:49
【问题描述】:
我目前正在使用 C# 和 WCF 开发 Web 服务。我需要制作一个上传方法,所以我关注this tutorial。现在我可以通过表单上传文件,文件上传到文件夹中,但在浏览器中总是返回错误(如在 ajax 中指定)这里所有代码:
IWebService.cs
[ServiceContract]
public interface IWebService
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/UploadFile?fileName={fileName}")]
void UploadFile(string fileName, Stream stream);
}
WebService.svc
public void UploadFile(string fileName, Stream stream)
{
string FilePath = Path.Combine(HostingEnvironment.MapPath("~/FileServer/Uploads"), fileName);
int length = 0;
using (FileStream writer = new FileStream(FilePath, FileMode.Create))
{
int readCount;
var buffer = new byte[8192];
while ((readCount = stream.Read(buffer, 0, buffer.Length)) != 0)
{
writer.Write(buffer, 0, readCount);
length += readCount;
}
}
}
TestClient.html
<head>
<script type="text/javascript">
function UploadFile() {
fileData = document.getElementById("fileUpload").files[0];
var data = new FormData();
$.ajax({
url: 'http://localhost:1945/Service1.svc/UploadFile?fileName=' + fileData.name,
type: 'POST',
data: fileData,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: "application/octet-stream", // Set content type to false as jQuery will tell the server its a query string request
success: function (data) {
alert('successful..');
},
error: function (data) {
alert('Some error Occurred!');
}
});
}
</script>
<title></title>
</head>
<body>
<div>
<div>
<input type="file" id="fileUpload" value="" />
<br />
<br />
<button id="btnUpload" onclick="UploadFile()">
Upload
</button>
</div>
</div>
</body>
【问题讨论】: