我已经制作了一个WCF服务方法来上传服务器上的文件,并希望传递其他相关值以及流,但是从jquery我无法做出错误,我怎么能这样做。
这是我的WCF方法。
public void UploadCustomFile(RemoteFileInfo request)
{
string FilePath = Path.Combine(HostingEnvironment.MapPath("~/Downloads"), "abc");
int length = 0;
using (FileStream writer = new FileStream(FilePath, FileMode.Create))
{
int readCount;
var buffer = new byte[8192];
while ((readCount = request.FileByteStream.Read(buffer, 0, buffer.Length)) != 0)
{
writer.Write(buffer, 0, readCount);
length += readCount;
}
}
}
这是我的RemoteFileInfo类:
[DataContract]
public class RemoteFileInfo : IDisposable
{
[DataMember]
public string FileName;
[DataMember]
public long Length;
[DataMember]
public System.IO.Stream FileByteStream;
public void Dispose()
{
if (FileByteStream != null)
{
FileByteStream.Close();
FileByteStream = null;
}
}
}
以下是jquery + html,
<body>
<div>
<input type="file" id="fileUpload" value="" />
<br />
<br />
<button id="btnUpload" onclick="UploadFile()">
Upload</button>
</div>
<button id="btnDownload" onclick="DownloadFile()">
Download</button>
<script type="text/javascript">
function UploadFile() {
// grab your file object from a file input
fileData = document.getElementById("fileUpload").files[0];
var data = new FormData();
$.ajax({
url: 'http://localhost:1398/AristMobileService.svc/UploadFile',
type: 'POST',
data: data,
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>
</body>
此外是json请求Body,我想在从jquery端发布数据时使用,
{
"FileByteStream":{
"__identity":{
"__identity":{
"__identity":null
}
}
},
"FileName":"String content",
"Length":9223372036854775807
}
答案 0 :(得分:0)
您甚至没有发送文件...您正在发送一个空的FormData对象。
至于包括两者,你需要使用FormData.append(key, value)
来设置你要发送的文件或数据的每一部分
您还可以将整个表单元素传递到new FormData(formelement)