HttpPostedFile 获取当前页面提交的文件

来源:互联网 发布:2017年网络暴力案例 编辑:程序博客网 时间:2024/05/21 19:33

Asp.net WebForm 获取当前页面提交的所有文件的方法

1
Context.Request.Files
1
Context.Request.Files.GetMultiple(Context.Request.Files.Keys[0]);

 获取文件属性和保存文件 

1
2
3
4
5
6
7
8
9
for (int i = 0; i < Context.Request.Files.Count; i++)
                {
                    var file = Context.Request.Files[i];
                    var length= file.ContentLength;
                    var type = file.ContentType;
                    var name = file.FileName;
                    var stream = file.InputStream;
                    file.SaveAs("filePath");
                }

   We need to add <httpModules> to Web.config that make sure SaveAs Method can work

 

1
2
3
<system.web>
<httpRuntime executionTimeout="500" maxRequestLength="153600" requestLengthDiskThreshold="153600"/>
</system.web>

  

FileUpload 源码中的SaveAs 也使用 Context.Request.Files 的SaveAs():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//------------------------------------------------------------------------------
// <copyright file="FileUpload.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
  
//
  
  
  
  
  
namespace System.Web.UI.WebControls {
  
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Linq;
    using System.IO;
    using System.Text;
    using System.Web.UI.HtmlControls;
  
  
    /// <devdoc>
    /// Displays a text box and browse button that allows the user to select a file for uploading.
    /// </devdoc>
    [ControlValueProperty("FileBytes")]
    [ValidationProperty("FileName")]
    [Designer("System.Web.UI.Design.WebControls.PreviewControlDesigner, " + AssemblyRef.SystemDesign)]
    public class FileUpload : WebControl {
  
        private static readonly IList<HttpPostedFile> _emptyFileCollection = new HttpPostedFile[0];
        private IList<HttpPostedFile> _postedFiles;
  
        public FileUpload() : base(HtmlTextWriterTag.Input) {
        }
  
        [
        Browsable(true),
        DefaultValue(false),
        WebCategory("Behavior"),
        WebSysDescription(SR.FileUpload_AllowMultiple)
        ]
        public virtual bool AllowMultiple {
            get {
                object o = ViewState["AllowMultiple"];
                return (o != null) ? (bool)o : false;
            }
            set {
                ViewState["AllowMultiple"] = value;
            }
        }
  
        /// <devdoc>
        /// Gets the byte contents of the uploaded file.  Needed for ControlParameters and templatized
        /// ImageFields.
        /// </devdoc>
        [
        Bindable(true),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public byte[] FileBytes {
            get {
                Stream fileStream = FileContent;
                if (fileStream != null && fileStream != Stream.Null) {
                    long fileStreamLength = fileStream.Length;
                    BinaryReader reader = new BinaryReader(fileStream);
                    Byte[] completeImage = null;
                     
                    if (fileStreamLength > Int32.MaxValue) {
                        throw new HttpException(SR.GetString(SR.FileUpload_StreamTooLong));
                    }
  
                    if (!fileStream.CanSeek) {
                        throw new HttpException(SR.GetString(SR.FileUpload_StreamNotSeekable));
                    }
  
                    int currentStreamPosition = (int)fileStream.Position;
                    int fileStreamIntLength = (int)fileStreamLength;
                    try {
                        fileStream.Seek(0, SeekOrigin.Begin);
                        completeImage = reader.ReadBytes(fileStreamIntLength);
                    }
                    finally {
                        // Don't close or dispose of the BinaryReader because doing so would close the stream.
                        // We want to put the stream back to the original position in case this getter is called again
                        // and the stream supports seeking, the bytes will be returned again.
                        fileStream.Seek(currentStreamPosition, SeekOrigin.Begin);
                    }
                    if (completeImage.Length != fileStreamIntLength) {
                        throw new HttpException(SR.GetString(SR.FileUpload_StreamLengthNotReached));
                    }
                    return completeImage;
                }
                return new byte[0];
            }
        }
  
  
        /// <devdoc>
        /// Gets the contents of the uploaded file.
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public Stream FileContent {
            get {
                HttpPostedFile f = PostedFile;
                if (f != null) {
                    return PostedFile.InputStream;
                }
  
                return Stream.Null;
            }
        }
  
  
        /// <devdoc>
        /// The name of the file on the client's computer, not including the path.
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public string FileName {
            get {
                HttpPostedFile postedFile = PostedFile;
                string fileName = string.Empty;
  
                if (postedFile != null) {
                    string fullFileName = postedFile.FileName;
  
                    try {
                        // Some browsers (IE 6, Netscape 4) return the fully-qualified filename,
                        // like "C:\temp\foo.txt".  The application writer is probably not interested
                        // in the client path, so we just return the filename part.
                        fileName = Path.GetFileName(fullFileName);
                    }
                    catch {
                        fileName = fullFileName;
                    }
                }
  
                return fileName;
            }
        }
  
  
        /// <devdoc>
        /// Whether or not a file was uploaded.
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public bool HasFile {
            get {
                // Unfortunately returns false if a 0-byte file was uploaded, since we see a 0-byte
                // file if the user entered nothing, an invalid filename, or a valid filename
                // of a 0-byte file.  We feel this scenario is uncommon.
                HttpPostedFile f = PostedFile;
                return f != null && f.ContentLength > 0;
            }
        }
  
        /// <devdoc>
        /// Whether or not at least 1 non-0-length file was uploaded.
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public bool HasFiles {
            get {
                // Unfortunately returns false if a 0-byte file was uploaded, since we see a 0-byte
                // file if the user entered nothing, an invalid filename, or a valid filename
                // of a 0-byte file.  We feel this scenario is uncommon.
                return PostedFiles.Any(f => f.ContentLength > 0);
            }
        }
  
  
        /// <devdoc>
        /// Provides access to the underlying HttpPostedFile.
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public HttpPostedFile PostedFile {
            get {
                if (Page != null && Page.IsPostBack) {
                    return Context.Request.Files[UniqueID];
                }
  
                return null;
            }
        }
  
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public IList<HttpPostedFile> PostedFiles {
            get {
                if (_postedFiles == null) {
                    IList<HttpPostedFile> result = _emptyFileCollection;
                    if (Page != null && Page.IsPostBack) {
                        result = Context.Request.Files.GetMultiple(UniqueID);
                        Debug.Assert(result != null);
                    }
                    _postedFiles = result;
                }
                return _postedFiles;
            }
        }
  
        protected override void AddAttributesToRender(HtmlTextWriter writer) {
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "file");
  
            if (AllowMultiple) {
                writer.AddAttribute(HtmlTextWriterAttribute.Multiple, "multiple");
            }
  
            string uniqueID = UniqueID;
            if (uniqueID != null) {
                writer.AddAttribute(HtmlTextWriterAttribute.Name, uniqueID);
            }
  
            base.AddAttributesToRender(writer);
        }
  
        protected internal override void OnPreRender(EventArgs e) {
            base.OnPreRender(e);
            HtmlForm form = Page.Form;
            if (form != null && form.Enctype.Length == 0) {
                form.Enctype = "multipart/form-data";
            }
        }
  
  
        protected internal override void Render(HtmlTextWriter writer) {
            // Make sure we are in a form tag with runat=server.
            if (Page != null) {
                Page.VerifyRenderingInServerForm(this);
            }
  
            base.Render(writer);
        }
  
  
        /// <devdoc>
        /// Initiates a utility method to save an uploaded file to disk.
        /// </devdoc>
        public void SaveAs(string filename) {
            HttpPostedFile f = PostedFile;
            if (f != null) {
                f.SaveAs(filename);
            }
        }
  
    }
}
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 锐志为什么停产 甲壳虫汽车停产 2019环保停产通知 南京炫赫门停产原因 2019甲壳虫停产还敢买吗 环保停产通知 glk300停产原因 高乐高为什么停产 大众r36为什么停产 娃哈哈格瓦斯停产原因 景逸x5为什么停产 荣耀note10为什么停产 2019探岳为什么停产 东风风光580为什么停产 五菱宏光s为什么停产 雪佛兰迈锐宝xl2019停产原因 比亚迪元为啥要停产 广汽传祺gs5为什么停产 比亚迪s6为什么停产 大众甲壳虫正式停产 河北2019所有工厂停产通知 北斗星x5为什么停产 五菱荣光v为什么停产 2018年飞鹤超级飞帆为什么停产 魅力中国杂志停刊了 心理月刊为什么停刊 知音漫客为什么停刊了 停工令 2019停工令 停工 停工留薪期 停工通知 停工令2019 工地停工 停工留薪 停工通知书 停工损失 武汉军运会停工通知 停工留薪期一般不超过 2019还停工吗 工地停工通知