ASP.net Web フォーム (v3.5) を取得して、プレーンな古い形式のファイルを投稿するにはどうすればよい<input type="file" />
ですか?
ASP.net FileUpload サーバー コントロールの使用には興味がありません。
ASP.net Web フォーム (v3.5) を取得して、プレーンな古い形式のファイルを投稿するにはどうすればよい<input type="file" />
ですか?
ASP.net FileUpload サーバー コントロールの使用には興味がありません。
あなたの aspx で:
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" id="myFile" name="myFile" />
<asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
</form>
コードビハインド:
protected void btnUploadClick(object sender, EventArgs e)
{
HttpPostedFile file = Request.Files["myFile"];
//check file was submitted
if (file != null && file.ContentLength > 0)
{
string fname = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
}
}
OPが質問で説明したように、サーバー側の制御に依存しないソリューションを次に示します。
クライアント側の HTML コード:
<form action="upload.aspx" method="post" enctype="multipart/form-data">
<input type="file" name="UploadedFile" />
</form>
upload.aspx の Page_Load メソッド:
if(Request.Files["UploadedFile"] != null)
{
HttpPostedFile MyFile = Request.Files["UploadedFile"];
//Setting location to upload files
string TargetLocation = Server.MapPath("~/Files/");
try
{
if (MyFile.ContentLength > 0)
{
//Determining file name. You can format it as you wish.
string FileName = MyFile.FileName;
//Determining file size.
int FileSize = MyFile.ContentLength;
//Creating a byte array corresponding to file size.
byte[] FileByteArray = new byte[FileSize];
//Posted file is being pushed into byte array.
MyFile.InputStream.Read(FileByteArray, 0, FileSize);
//Uploading properly formatted file to server.
MyFile.SaveAs(TargetLocation + FileName);
}
}
catch(Exception BlueScreen)
{
//Handle errors
}
}
toのenctype
属性を設定する必要があります。その後、コレクションを使用してアップロードされたファイルにアクセスできます。form
multipart/form-data
HttpRequest.Files
runat サーバー属性で HTML コントロールを使用する
<input id="FileInput" runat="server" type="file" />
次に、asp.net Codebehind で
FileInput.PostedFile.SaveAs("DestinationPath");
興味がある場合に進行状況を表示するサードパーティのオプションもいくつかあります
はい、ajax post メソッドでこれを実現できます。サーバー側では、httphandler を使用できます。そのため、要件に応じてサーバー コントロールを使用していません。
ajax を使用すると、アップロードの進行状況も表示できます。
ファイルを入力ストリームとして読み取る必要があります。
using (FileStream fs = File.Create("D:\\_Workarea\\" + fileName))
{
Byte[] buffer = new Byte[32 * 1024];
int read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
while (read > 0)
{
fs.Write(buffer, 0, read);
read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
}
}
サンプルコード
function sendFile(file) {
debugger;
$.ajax({
url: 'handler/FileUploader.ashx?FileName=' + file.name, //server script to process data
type: 'POST',
xhr: function () {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return myXhr;
},
success: function (result) {
//On success if you want to perform some tasks.
},
data: file,
cache: false,
contentType: false,
processData: false
});
function progressHandlingFunction(e) {
if (e.lengthComputable) {
var s = parseInt((e.loaded / e.total) * 100);
$("#progress" + currFile).text(s + "%");
$("#progbarWidth" + currFile).width(s + "%");
if (s == 100) {
triggerNextFileUpload();
}
}
}
}
Request.Files コレクションには、FileUpload コントロールまたは手動で作成され<input type="file">
た .
そのため、Web フォームの途中にプレーンな古いファイル入力タグを記述してから、Request.Files コレクションからアップロードされたファイルを読み取ることができます。
他の人が答えているように、Request.Files は、投稿されたすべてのファイルを含む HttpFileCollection です。次のように、そのオブジェクトにファイルを要求するだけで済みます。
Request.Files["myFile"]
しかし、同じ属性名を持つ入力マークアップが複数ある場合はどうなるでしょうか。
Select file 1 <input type="file" name="myFiles" />
Select file 2 <input type="file" name="myFiles" />
サーバー側では、前のコード Request.Files["myFile"] は、2 つのファイルではなく、1 つの HttpPostedFile オブジェクトのみを返します。私は .net 4.5 で GetMultiple という拡張メソッドを見てきましたが、以前のバージョンでは存在しませんでした。そのため、拡張メソッドを次のように提案します。
public static IEnumerable<HttpPostedFile> GetMultiple(this HttpFileCollection pCollection, string pName)
{
for (int i = 0; i < pCollection.Count; i++)
{
if (pCollection.GetKey(i).Equals(pName))
{
yield return pCollection.Get(i);
}
}
}
この拡張メソッドは、存在する場合、HttpFileCollection に「myFiles」という名前を持つすべての HttpPostedFile オブジェクトを返します。
私はこれをずっと使ってきました。
//create a folder in server (~/Uploads)
//to upload
File.Copy(@"D:\CORREO.txt", Server.MapPath("~/Uploads/CORREO.txt"));
//to download
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName("~/Uploads/CORREO.txt"));
Response.WriteFile("~/Uploads/CORREO.txt");
Response.End();