要進行上傳,您需要有一個文件輸入和一個使用multipart/form-data enctype的表單。在服務器上,您從Request.Files集合元素中獲得一個與您的輸入標記名稱匹配的HttpPostedFileBase對象。然後你訪問文件對象上的流並讀取它。
一旦你有了數據,你就可以執行你的轉換 - 在這裏你正在讀取一個特定標籤的數量。然後你想從你的動作中返回一個FileResult。由於它實際上只是一個字符串,我建議將它寫入一個MemoryStream,然後倒回該字符串並從中創建一個FileResult。
<% using (Html.BeginForm("Upload","Controller",FormMethod.Post, new { enctype = "multipart/form-data"))
{ %>
<label for="uploadFile">File:</label>
<input type="file" name="uploadFile" id="uploadFile" />
<input type="submit" value="Upload" />
<% } %>
代碼 - 因爲我認爲你最終想要做更復雜的東西,我會包含一些(未經測試/未編譯)不,你描述了什麼代碼(我認爲)。
public ActionResult Upload()
{
var file = Request.Files["uploadFile"];
if (file == null)
{
ModelState.AddModelError("uploadFile", "No file specified");
return View();
}
var reader = new StreamReader(file.InputStream);
var doc = XDocument.Load(reader);
var count = doc.Descendants().Where(n => n.Name == "basket").Count();
var output = new MemoryStream();
var writer = new StreamWriter(output);
writer.Write("{0} baskets", count);
output.Seek(0, SeekOrigin.Begin);
return File(output, "text/plain", "count.txt");
}
這太棒了!我一回到午餐時間就會嘗試一下。謝謝你的幫助。 – 2009-10-31 13:46:42