更新的问题:
我正在尝试创建一个将主题、内容和文件传递给网络服务的表单。这是我到目前为止所拥有的,想知道是否有人可以告诉我我是否朝着正确的方向前进,以及如何做我在 asmx 文件的注释中突出显示的位
HTML:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form action="files.asmx/CaptureFile" enctype="multipart/form-data" method="post">
<input type="text" name="subject" /><br />
<input type="text" name="content" /><br />
<input type="file" name="filedata" /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
网络服务:
<%@ WebService Language="C#" Class="Files" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Script;
using System.Web.Script.Services;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
[ScriptService]
public class Files : WebService {
SqlConnection connection;
SqlCommand command;
SqlDataReader reader;
int intAffectedRows;
[WebMethod()]
public int CaptureFile(string subject, string content, byte[] filedata)
{
// somehow reconstruct the filedata to an actual file saved on the server
// save subject, content, and filename to database
using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"]))
{
using (command = new SqlCommand("query to save subject content and filename_only to database", connection))
{
command.Parameters.Add("@subject", SqlDbType.VarChar, 255).Value = subject;
command.Parameters.Add("@content", SqlDbType.VarChar, 255).Value = content;
command.Parameters.Add("@filedata", SqlDbType.VarChar, 255).Value = filedata; // need to save filename here, not file binary data
connection.Open();
intAffectedRows = command.ExecuteNonQuery();
connection.Close();
}
}
return intAffectedRows;
}
}
------------
原始问题:
我了解如何将标准文本发送到网络服务器,对其进行处理,然后发回一些内容,即
[WebMethod()]
public List<Notification> GetNotification(int id)
{
// do processing here
// return something back
return "Notification text";
}
我的 ajax 看起来像这样:
$.ajax({
type: 'POST',
url: '/webservices/notifications.asmx/GetNotification',
data: '{id: ' + number + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
如何发送文件?该文件将是 .pdf 或 .doc 文件,因此我可以将其与一些文本一起保存到服务器。所以,我想要一个主题文本框,然后选择文件按钮/文本框来选择文件,以及一个提交按钮。当填写完 2 个文本框并单击提交按钮后,它应该将主题和文件发送到网络服务,网络服务会将主题和文件位置保存到数据库中,并将实际文件保存到服务器。
另外,我是在内网环境下开发,IE对本地内网是完全信任的。
最佳答案
How do I send a file?
您不能使用 AJAX 发送文件,因为使用 javascript 您无权访问客户端计算机上的文件系统,因此您无法获取文件内容。如果你想将文件发送到网络服务器,你可以使用 <form>
使用文件输入和 enctype="multipart/form-data"
这将发布到服务器端脚本。然后,此脚本可以调用 Web 服务并将文件内容作为字节数组传输。
关于c# - 将文件发送到 Web 服务 (asmx),以便将其保存在服务器上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8757123/