你好我想从webservice而不是WCF上传文件。我正在使用C#并将其与web应用程序一起使用。从Web应用程序发送文件,服务将接受该文件(文本文件)并放在网站的上传文件夹中具体位置。
为此我创建了像这样的webservice
:用于制作网络服务
创建空的Web应用程序 - >选择新项目 - >网络服务
1>在webservice中写下以下代码
public System.IO.Stream FileByteStream;
[WebMethod]
public void UploadFile()
{
FileStream targetStream = null;
Stream sourceStream = FileByteStream;
string uploadFolder = @"D:\UploadFile";
string filePath = Path.Combine(uploadFolder, @"C:\Users\maya\Desktop\test.txt");
using (targetStream = new FileStream(filePath, FileMode.Create,
FileAccess.Write, FileShare.None))
{
//read from the input stream in 65000 byte chunks
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
// save to output stream
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
这里我没有接受任何输入,我手动输入了一个文本文件。我想将该文件传输到uploadfolder。我收到了这个错误:
HTTP 500内部服务器错误
在这一行:
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
如何处理?
答案 0 :(得分:0)
我使用aspx页面而不是webservice.I使用jquery这样做。它就像一个魅力。
所以让它成为你的文件上传控件。
<div>
<input type="file" name="UploadFile" id="txtUploadFile" />
</div>
这是jquery代码
$('#txtUploadFile').on('change', function (e) {
var files = e.target.files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++){
data.append("file" + x, files[x]);
}
$.ajax({
type: "POST",
url: '/Upload.aspx', //put the complete url here like http://www.example.com/Upload.aspx
contentType: false,
processData: false,
data: data,
success: function(result) {
console.log(result);
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}
});
这是我的aspx代码
public partial class Upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
UploadFile(sender, e);
}
}
protected void UploadFile(object sender, EventArgs e)
{
try
{
HttpFileCollection fileCollection = Request.Files;
string savedfile = "";
for (int i = 0; i < fileCollection.Count; i++)
{
try
{
HttpPostedFile upload = fileCollection[i];
int f = fileCollection[i].ContentLength;
string filename = "/ProductImages/" + fileCollection[i].FileName;
upload.SaveAs(Server.MapPath(filename));
savedfile += fileCollection[i].FileName;
}
catch (Exception ex)
{
}
}
}
catch(Exception ex)
{
List<string> ff = new List<string>();
ff.Add(ex.Message.ToString());
System.IO.File.WriteAllLines(Server.MapPath("/ProductImages/Error.txt"), ff);
}
}
}