ASP.Net中上传文件的几种方法
在做Web项目时,上传文件是经常会碰到的需求。ASP.Net的WebForm开发模式中,封装了FileUpload控件,可以方便的进行文件上传操作。但有时,你可能不希望使用ASP.Net中的服务器控件,仅仅使用Input标签来实现文件上传。当然也是可以的。下面总结在项目中使用过的上传文件的方式。
一、使用Asp.Net中的FileUpload服务器端控件实现上传
使用asp.net中的服务器端控件FileUpload上传文件非常方便。FileUpload对上传操作进行了封装,你只需要调用SaveAs方法即可完成上传。下面是简单的上传代码。
p服务器端控件上传/p
asp:FileUpload ID="MyFileUpload" runat="server" /
asp:Button ID="FileUploadButton" runat="server" Text="上传"
οnclick="FileUploadButton_Click" /
1 protected void FileUploadButton_Click(object sender, EventArgs e)
2 {
3 if (MyFileUpload.HasFile)
4 {
5 string filePath = Server.MapPath("~/UploadFiles/");
6 string fileName = MyFileUpload.PostedFile.FileName;
7 MyFileUpload.SaveAs(filePath + fileName);
8 Response.Write("p 上传成功!/p");
9 }
10 else
11 {
12 Response.Write("p 请选择要上传的文件!/p");
13 }
14 }
当然,在实际项目中就不能这么简单的保存文件了。你至少得增加一些文件类型的判断,防止用户上传一些能够威胁到系统安全的文件。你可以采用客户端JS验证的方式,也能够在.cs的服务器端代码中验证。
在asp.Net WebForm开发框架下,我们也可以利用Html的Input标签来上传文件。这时候需要注意的一点,这个type为file的Input标签需要加上runat="server"属性,否则在后台Request.Files获取不到上传的文件。
p使用Html的Input标签上传/p
input type="file" name="MyFileUploadInput" runat="server" /asp:Button
ID="InputFileUploadButton" runat="server" Text="上传"
οnclick="InputFileUploadButton_Click" /
1 protected void InputFileUploadButton_Click(object sender, EventArgs e)
2 {
3 HttpFileCollection files = Request.Files;
4 string filePath = Server.MapPath("~/UploadFiles/");
5 if (files.Count != 0)
6 {
7 string fileName = files[0].FileName;
8 files[0].SaveAs(Path.Combine(filePath, fileName));
9 Response.Write("p上传成功/p");
10 }
11 else
12 {
13 Response.Write("p未获取到Files:"+ files.Count.ToString()+"/p");
14 }
15 }
以这种方式进行上传的时候,好处就是可以方便的用JS生成多个Input标签来上传多个文件。且此时需要注意的是,Input标签必须要有name属性。在后台,只需要循环调用SaveAs()方法即可。
接下来的两种上传方式(二和三)都会用到Ajax异步提交数据,后台使用一个.ashx文件进行处理。两种方式共用一个文件,ajax传入的url参数中加一个method来区分哪种方式传过来的。后台代码如下:
1 public void ProcessRequest(HttpContext context)
2 {
3 string method = context.Request.QueryString["method"].ToString();
4 switch (method)
5 {
6 case "ajaxFileUpload":
7 ajaxFileUpload(context);
8 break;
9 case "formDataUpload":
10 formDataUpload(context);
11 break;
12 default:
13 break;
14 }
15 }
16
17 private static void formDataUpload(HttpContext context)
18 {
19 HttpFileCollection files = context.Request.Files;
20
21 string msg = string.Empty;
22 string error = string.Empty;
23 if (files.Count 0)
24 {
25 files[0].SaveAs(ConfigurationManager.AppSettings["FilePath"].ToString() + System.IO.Path.GetFileName(files[0].FileName));
26 msg = " 成功! 文件大小为:" + files[0].ContentLength;
27 string res = "{ error:'" + error + "', msg:'" + msg + "'}";
28 context.Response.Write(res);
29 context.Response.End();
30 }
31 }
32
33 private static void ajaxFileUpload(HttpContext context)
34 {
35 HttpFileCollection files = context.Request.Files;
36
37 string msg = string.Empty;
38 string error = string.Empty;
39 if (files.Count 0)
40 {
41 files[0].SaveAs(ConfigurationManager.AppSettings["FilePath"].ToString() + System.IO.Path.GetFileName(files[0].FileName));
42 msg = " 成功! 文件大小为:" + files[0].ContentLength;
43 string res = "{ error:'" + error + "', msg:'" + msg + "'}";
44 context.Response.Write(res);
45 context.Response.End();
46 }
47 }
二、使用Html中的Input标签加FormData对象实现
使用这种方式上传附件,对浏览器有些要求。FormData属于Html5中新增的特性,IE浏览器只有在10以上才支持。所以,个中利弊自己权衡,但用起来觉得方便。下面直接上代码:
1 function formDataUpload() {
2 var fileupload = document.getElementById('fileToUpload').files;
3 var formdata = new FormData();
4 formdata.append('files', fileupload[0]);
5 var xmlHttp = new XMLHttpRequest();
6 xmlHttp.open("post", 'Handlers/FileUpload.ashxmethod=formDataUpload');
7 xmlHttp.onreadystatechange = function () {
8 if (xmlHttp.readyState == 4 xmlHttp.status == 200) {
9 alert('上传成功');
10 }
11 }
12 xmlHttp.send(formdata);
13 }
三、使用Jquery中的ajaxfileupload.js插件实现上传
使用此方法,需要引用jquery.js和ajaxfileupload.js两个文件。还需要注意的部分是两个文件的版本匹配问题,可能在使用过程中会出现些异常。此时发挥搜索引擎的作用,总能找到你需要的解决方案。
JavaScript代码如下:
1 function ajaxFileUpLoad() {
2 $.ajaxFileUpload(
3 {
4 url: 'Handlers/FileUpload.ashxmethod=ajaxFileUpload',
5 secureuri: false,
6 fileElementId: 'fileToUpload',
7 dataType: 'json',
8 success: function (data, status) {
9 $('#img1').attr("src", data.imgurl);
10 if (typeof (data.error) != 'undefined') {
11 if (data.error != '') {
12 alert(data.error);
13 } else {
14 alert(data.msg);
15 }
16 }
17 },
18 error: function (data, status, e) {
19 alert(e);
20 }
21 }
22 )
23 return false;
24 }
Html页面上的代码如下:
1 html xmlns="http://www.w3.org/1999/xhtml"
2 head
3 script type="text/javascript" src="Scripts/jquery-1.4.1.js"/script
4 script type="text/javascript" src="Scripts/ajaxfileupload.js"/script
5 script type="text/javascript"
6 $(function () {
7 $("#ajaxfileuploadButton").click(function () {
8 ajaxFileUpLoad();
9 })
10
11 $("#formdataButton").click(function () {
12 formDataUpload();
13 })
14 });
15
16 /script
17 title/title
18 script type="text/javascript"
19
20 /script
21 /head
22 body
23 input type="file" id="fileToUpload" name="fileToUpload" /
24 input type="button" id="ajaxfileuploadButton" value="ajaxfileupload插件上传" /
25 input type="button" id="formdataButton" value="FormData方式上传" /
26 /body
27 /html
总结
以上总结了几种上传文件的方式,也简单的说明了一些使用中需要注意的问题。当然,可能遇到的问题还不止这些,如果在开发过程中还遇到了其他稀奇古怪的问题,可自行搜索相关问题。每一次针对遇到的问题的解决,都是对这方面的知识一次更深入的理解。在不断解决问题中慢慢进步。
https://www.cnblogs.com/gxwang/p/4883902.html
ASP.Net中上传文件的几种方法 相关文章
post接口调用 vue
(1) api.js文件 1 import axios from 'axios'2 3 export const insertTask = (data, cb,err) = {4 axios.request({5 url: `${MODULE_URL}/insertTask`,6 method: 'post',7 data8 }).then(cb).catch(err);9 } vue文件 1 let data = { 2 name:'****' 3 } 4 ins
邮件发送定时操作
1邮件发送 1.1编写配置文件 #QQ邮箱spring.mail.username=2082620872@qq.com#密码spring.mail.password=rntexrvtuhmvefia#固定的spring.mail.host=smtp.qq.com#开启加密验证spring.mail.properties.mail.smtp.ssl.enable=true 1.2导入依赖 dependency groupI
node批量修改文件文本内容
node批量修改文件文本内容,默认会将文件夹下的所有包含指定字符串的文件替换,拿来玩 文本内容替换 执行 生成结果 replaceContent.js var fs = require("fs");var path = require("path");replaceContent("test", "8888", "p666p");function replaceContent(f
bootstrap文件上传参数解析
$(function () { initFileInput("input-id"); }) function initFileInput(ctrlName) { var control = $('#' + ctrlName); control.fileinput({ language: 'zh', //设置语言 uploadUrl: "/fileStore/open/upload/file", //上传的地址 allowedFileExtensions:
解决安装Pycharm后在C盘下生成大文件的问题
前言 上次在整理 C 盘时,无意间发现了一个这样的文件。在 我的用户目录 下,有个 .PyCharm2019.3 这样的文件夹,我猜想和Pycharm可能有什么py关系。 那这个文件有多大呢,来操作一下康康。 雾草,竟然0.5个G了,我才刚用没多久唉! 这对于我这强迫症来说很难受哎,
Entity Framework Core 3.1 入门(八)在 ASP.NET Core 中配置 Entity Framework Core
此入门教程是记录下方参考资料视频的过程,本例基于Entity Framework Core 3.1 开发工具:Visual Studio 2019 参考资料:https://www.bilibili.com/video/BV1xa4y1v7rR 创建 ASP.NET Core 项目 在解决方案 Demo 下新建ASP.NET Core 项目,命名为 Demo.Web 使
python查看与改变文件的编码格式
查看文件的编码格式 with open(r"C:\Users\Administrator\Desktop\111\2.1 (1)smile.txt", 'rb+') as fp: content = fp.read() print(chardet.detect(content)) #{'encoding': 'UTF-8-SIG', 'confidence': 1.0, 'language': ''} 修改文件的编码格式 with ope
Redis整合springboot
1.编写配置文件properject #配置本机端口号spring.redis.host=127.0.0.1spring.redis.port=6379 2.导入依赖 dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-redis/artifactId /dependency 3.使用 //redis配置类 @A
HTML 5 详解之表单拓展三:列表框_文本域_文件域
!DOCTYPE htmlhtml lang="en"head meta charset="UTF-8" title表单拓展三之列表框_文本域_文件域/title/headbodyh1注册/h1!--表单:action:表单提交的位置,可以是网站,也可以是一个请求处理地址method:get/post 表单的两种提交方式,为确保数据安全常用 pos
深入Jar包:Gradle构建可执行jar包与访问jar包中文件夹与文件
前言 Java的跨平台功能听起来很诱人可口,号称“Write Once,Run Everywhere”,实际上是“Run Once,Debug Everywh”... 在实际开发过程中还是会遇到各种各样的坑的,刚刚解决了一系列问题,特地写个文章总结一下。 使用Gradle构建Jar包 感谢万能的Gradle,