[英]Sending files to a webservice (asmx) so it can be saved on the server
更新的問題:
我正在嘗試創建一個將主題,內容和文件傳遞給Web服務的表單。 這就是我到目前為止所想的,並且想知道是否有人可以告訴我我是否朝着正確的方向前進,以及如何在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:
<%@ 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;
}
}
原始問題:
我理解如何將標准文本發送到Web服務器,處理它,然后發回一些東西,即
[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個文本框並單擊提交按鈕時,它應該將主題和文件發送到Web服務,即web服務將主題和文件位置保存到數據庫,並將實際文件保存到服務器。
此外,我正在內部網環境中開發,IE完全信任本地Intranet。
我如何發送文件?
您不能使用AJAX發送文件只是因為使用javascript您無法訪問客戶端計算機上的文件系統,因此您無法獲取文件內容。 如果要將文件發送到Web服務器,可以使用帶有文件輸入的<form>
和enctype="multipart/form-data"
,它將發布到服務器端腳本。 然后,該腳本可以調用Web服務並將文件內容作為字節數組傳輸。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.