使用asp.net webservice上传文件

本文关键字:文件 webservice asp net 使用 | 更新日期: 2023-09-27 18:13:53

你好,我想从webservice而不是WCF上传文件。我正在使用c#和消费它与web应用程序。从web应用程序发送文件,服务将接受该文件(文本文件)并将其放置在网站/或特定位置的上传文件夹中。

为此,我创建了如下的webservice

:用于创建webservice

创建空web应用程序->选择新项目-> 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)

如何处理?

使用asp.net webservice上传文件

我使用aspx页面而不是webservice。我使用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);
        }
    }
}