① mvc视图中怎么上传图片并显示
如果只是上传的话那太容易了,如果还要显示那就难了,因为要显示的话就不能只向服务器提交一次请求,必须异步提交。下面的例子是我亲自写的,异步提交上传图片并预览。全部代码都在。
返回到前台页面的jsON格式对象是以类的对象。
publicclassReturnImage
{
publicstringbig{get;set;}
publicstringsmall{get;set;}
publicstringisSuccessfull{get;set;}
publicstringmessage{get;set;}
}
对于上传和生成缩略图,请自行完成,以下是ASP.NETMVC的例子。
publicclassHomeController:Controller
{
//
//GET:/Home/
publicActionResultIndex()
{
returnView();
}
///<summary>
///上传图片
///</summary>
///<returns></returns>
publicActionResultUploadImage()
{
//定义错误消息
JsonResultmsg=newJsonResult();
try
{
//接受上传文件
HttpPostedFileBasepostFile=Request.Files["upImage"];
if(postFile!=null)
{
DateTimetime=DateTime.Now;
//获取上传目录转换为物理路径
stringuploadPath=Server.MapPath("~/UploadFiles/"+time.Year+"/"+time.ToString("yyyyMMdd")+"/");
//文件名
stringfileName=time.ToString("yyyyMMddHHmmssfff");
//后缀名称
stringfiletrype=System.IO.Path.GetExtension(postFile.FileName);
//获取文件大小
longcontentLength=postFile.ContentLength;
//文件不能大于2M
if(contentLength<=1024*2048)
{
//如果不存在path目录
if(!Directory.Exists(uploadPath))
{
//那么就创建它
Directory.CreateDirectory(uploadPath);
}
//保存文件的物理路径
stringsaveFile=uploadPath+fileName+"_big"+filetrype;
try
{
//保存文件
postFile.SaveAs(saveFile);
//保存缩略图的物理路径
stringsmall=uploadPath+fileName+"_small"+filetrype;
MakeThumbnail(saveFile,small,320,240,"W");
ReturnImageimage=newReturnImage();
image.big="/UploadFiles/"+time.Year+"/"+time.ToString("yyyyMMdd")+"/"+fileName+"_big"+filetrype;
image.small="/UploadFiles/"+time.Year+"/"+time.ToString("yyyyMMdd")+"/"+fileName+"_small"+filetrype;
msg=Json(image);
}
catch
{
msg=Json("上传失败");
}
}
else
{
msg=Json("文件大小超过限制要求");
}
}
else
{
msg=Json("请选择文件");
}
}
catch(Exceptione)
{
;
}
msg.ContentType="text/html";
returnmsg;
}
///<summary>
由于回答超过最大限制,///生成缩略图的代码请向我索取
② js文件上传fileupload(js文件上传后端是如何拿到文件的)
js如何上传文件方式一:事先写好多个input.在点击时才显示。也就是说上传的最大个数是写死了的。
第六步:上传文件点击确定按钮,即可将文件上传到本地磁盘,上传成功后自动跳转到根目录。
既然可以循环多文件的话,就可以尝试多文件上传了。首先创建XMLHttpRequest对象//这是全局变量。
怎样用JS控制文件上传时FILE控件内默认的文件类型accept属性只能与配合使用。它规定能够通过文件上传进行提交的文件类型。提示:请避免使用该属性。应该在服务器端验证文件上传。
,文件类型:+file.type+,文件大小:+file.sizedocument.body.appendChild(div)}}既然可以循环多文件的话,就可以尝试多文件上传了。首先创建XMLHttpRequest对象//这是全局变量。
js采用FileAPI来上传文件的。FileAPI由一组javaScript对象以及事件构成。赋予开发人员操作在文件选择控件中选定文件的能力。图1展示了FileAPI所有的JavaScript的组合关系。
你要上传的文件是什么格式,在js里面添加这个这个格式的后缀。
jquery.fileUpload.js文件上传问题可能是上传的文件太大,你换一个小一点的看看,几百k的。或者开启一下你后端语言的错误提示,看下是什么错误。
要实现下面这样一个js方法:file_upload(文件内容,URL){//用jQuery将文件内容传送至URL...}不用任何jQuery插件,请问如何实现上述功能。
ajaxFileUpload是一个异步上传文件的jQuery插件,语法:$.ajaxFileUpload([options])。使用方法:第一步:先引入jQuery与ajaxFileUpload插件。注意先后顺序。
我的理解是你应该先通过图片上传接口把图片上传到服务器上(上传后的服务器端的图片地址,保存到里),然后再统一提交所有的表单项。
获取jQuery集合的某一项对于获取的元素集合,获取其中的某一项(通过索引指定)可以使用eq或get(n)方法或者索引号获取,要注意,eq返回的是jquery对象,而get(n)和索引返回的是dom元素对象。
我使用了ajaxFileUpload这个js来实现不借助form表单的不刷新页面提交文件的功能(但是其实这个js内部还是用的是form表单提交的233,伪ajax,和jQueryajax是不一样的)。
我需要一个js或者jquery能批量上传图片+预览的功能。急~~~急~~~急...//初始化WebUploadervaruploader=WebUploader.create({//选完文件后,是否自动上传。auto:true,//swf文件路径swf:BASE_URL+/js/Uploader.swf,//文件接收服务端。
本地预览肯定是不行的,这是浏览器出于安全考虑的限制。不过可以使用伪ajax见把图片上传到服务器,然后在预览。
批量上传?js就用Jquery上传控件吧(开源社区里面有例子)。
可以批量上传图片什么的以及可以预览的都是用flash来实现的js最多只能单张上传,还不能预览。
分片与并发结合,将一个大文件分割成多块,并发上传,极大地提高大文件的上传速度。当网络问题导致传输错误时,只需要重传出错分片,而不是整个文件。另外分片传输能够更加实时的跟踪上传进度。
③ jquery.fileUpload.js文件上传问题
了解,fileuploader方法需要先初始化,然后才能触发上传,并不需要你手动触发change事件
你只版需
html
<form>
file:<inputtype="file"id="file"name="file">
</form>
js
$('#file').on('change',function(){
//这里可权以做校验,返回false就不会触发下面的上传插件,否则就会触发上传
if(!this.value||this.value.indexOf('.jpg')==-1){
returnfalse;
}
});
//初始化上传插件
$('#file').fileupload({
autoUpload:true,//这里为true,则选中文件后就会自动上传
url:'',
done:$.noop,
fail:$.noop
});
④ 用jquery如何实现提交表单点击提交之后显示正在上传中,之后显示上传成功的效果
需要准备的材料分别有:电脑、html编辑器、浏览器。
1、首先,打开html编辑器,新建html文件,回例如答:index.html,并引入jquery。
⑤ js文件上传的几种方式(js文件上传)
javaweb前端上传文件到后台常用的几种方式1、使用form表单提交
但是这里要记得添加enctype属性,这个属性是指定form表单在向服务器提交之前,对表单数据如何进行编码。文件域中的name="file"属性的值,需要和后台接收的对象名一致,不然接收不到。
2、使用ajax提交文件
使用ajax提交首先引入jquery-form.js文件才能实现,接着使用上面的html代码,加入以js则可以实现ajax提交文件。
3、使用FormData对象
4、后台接收文件,框架采用的SpringBoot微服务框架,因为该框架搭建很方便所以采用这个框架写例子。
js如何上传文件js采用FileAPI来上传文件的。
FileAPI由一组JavaScript对象以及事件构成。赋予开发人员操作在inputtype=”file”…/文件选择控件中选定文件的能力。图1展示了FileAPI所有的JavaScript的组合关系。
FileAPI简单示例
body
h1FileAPIDemo/h1
p
!--用于文件上传的表单元素--
formname="demoForm"id="demoForm"method="post"enctype="multipart/form-data"
action="javascript:uploadAndSubmit();"
pUploadFile:inputtype="file"name="file"//p
pinputtype="submit"value="Submit"//p
/form
divProgessing(inBytes):spanid="bytesRead"
/span/spanid="bytesTotal"/span
/div
/p
/body
运行效果:
几种js实现的动态多文件上传
方式一:事先写好多个input.在点击时才显示。也就是说上传的最大个数是写死了的。
html
p
ahref='#'onclick='javascript:viewnone(more1)'添加附件/a
divid='more1'style='display:none'
inputtype="file"name="attach1"size="50"javascript:viewnone(more2)
/span
/div
divid='more2'style='display:none'
inputtype="file"name="attach2"size="50"'
/div
/p
js
SCRIPTlanguage="javascript"
functionviewnone(e){
e.style.display=(e.style.display=="none")?"":"none";
}
/script
方式二:这种方式的动态多文件上传是实现了的,很简单的,不说废话看code
html
inputtype="button"name="button"value="添加附件"onclick="addInput()"
inputtype="button"name="button"value="删除附件"onclick="deleteInput()"
spanid="upload"/span
js
scripttype="text/javascript"
varattachname="attach";
vari=1;
functionaddInput(){
if(i0){
varattach=attachname+i;
if(createInput(attach))
i=i+1;
}
}
functiondeleteInput(){
if(i1){
i=i-1;
if(!removeInput())
i=i+1;
}
}
functioncreateInput(nm){
varaElement=document.createElement("input");
aElement.name=nm;
aElement.id=nm;
aElement.type="file";
aElement.size="50";
//aElement.value="thanks";
//aElement.onclick=Function("asdf()");
if(document.getElementById("upload").appendChild(aElement)==null)
returnfalse;
returntrue;
}
functionremoveInput(nm){
varaElement=document.getElementById("upload");
if(aElement.removeChild(aElement.lastChild)==null)
returnfalse;
returntrue;
}
/script
方式三:动态多文件上传,只是在oFileInput.click();这个地方,这样做就不能上传这个文件了,因为发现它在上传之时就把这个input中的文件置空了。很可能是为了安全着想吧!
另外还有一点就是说,click()只有在ie中才能正常运行。
虽说这种方式最终没能实现上传,但还是留下来参考,看看是否有人可以真正实现上传。
html
Ahref="javascript:newUpload();"添加附件/A
TABLEwidth="100%"border="0"cellpadding="0"cellspacing="1"
TBODYid="fileList"/TBODY
/TABLE
DIVid="uploadFiles"style="display:block"/DIV
js
SCRIPTlanguage="javascript"
//---新建上传
functionnewUpload(){
varoFileList=document.getElementById("fileList");
varfileCount=oFileList.childNodes.length+1;
varoFileInput=newFileInput("upfile_"+fileCount);
if(selectFile(oFileInput)){
addFile(oFileInput);
}
}
//----选择文件
functionselectFile(oFileInput){
varoUploadFiles=document.getElementById("uploadFiles");
oUploadFiles.appendChild(oFileInput);
oFileInput.focus();
oFileInput.click();//不能这样做,可能是为了安全着想吧!
varfileValue=oFileInput.value;
if(fileValue==""){
oUploadFiles.removeChild(oFileInput);
returnfalse;
}
else
returntrue;
}
//---新建一个文件显示列表
functionaddFile(oFileInput){
varoFileList=document.getElementById("fileList");
varfileIndex=oFileList.childNodes.length+1;
varoTR=document.createElement("TR");
varoTD1=document.createElement("TD");
varoTD2=document.createElement("TD");
oTR.setAttribute("id","file_"+fileIndex);
oTR.setAttribute("bgcolor","#FFFFFF");
oTD1.setAttribute("width","6%");
oTD2.setAttribute("width","94%");
oTD2.setAttribute("align","left");
oTD2.innerText=oFileInput.value;
oTD1.innerHTML='Ahref="javascript:removeFile('+fileIndex+');"删除/A'
oTR.appendChild(oTD1);
oTR.appendChild(oTD2);
oFileList.appendChild(oTR);
}
//---移除上传的文件
functionremoveFile(fileIndex){
varoFileInput=document.getElementById("upfile_"+fileIndex);
varoTR=document.getElementById("file_"+fileIndex);
uploadFiles.removeChild(oFileInput);
fileList.removeChild(oTR);
}
//---创建一个fileinput对象并返回
functionnewFileInput(_name){
varoFileInput=document.createElement("INPUT");
oFileInput.type="file";
oFileInput.id=_name;
oFileInput.name=_name;
oFileInput.size="50";
//oFileInput.setAttribute("id",_name);
//oFileInput.setAttribute("name",_name);
//oFileInput.outerHTML='INPUTtype=fileid='+_name+'name='+_name+''
//alert(oFileInput.outerHTML);
returnoFileInput;
}
/SCRIPT
⑥ jqueryajax不能上传图片
不能上传的原因可能是jquery插件使用不正确。
解决方法:
1、在head之间加入jquery引用
<scripttype="text/javascript" src="jquery.js"></script>
<scriptsrc="project/js/jquery.form.js" type="text/javascript"></script>
<scriptsrc="project/js/fileload.js" type="text/javascript"></script>
2、定义fileload.js,代码如下:
function createHtml(obj) {
var htmstr = [];
htmstr.push( "<form id='_fileForm' enctype='multipart/form-data'>");
htmstr.push( "<table cellspacing="0" cellpadding="3" style="margin:0 auto; margin-top:20px;">");
htmstr.push( "<tr>");
htmstr.push( "<td class="tdt tdl">请选择文件:</td>");
htmstr.push( "<td class="tdt tdl"><input id="loadcontrol" type="file" name="filepath" id="filepath" /></td>");
htmstr.push( "<td class="tdt tdl tdr"><input type="button" onclick="fileloadon()" value="上传"/></td>");
htmstr.push( "</tr>");
htmstr.push( "<tr> <td class="tdt tdl tdr" colspan='3'style='text-align:center;'><div id="msg"> </div></td> </tr>");
htmstr.push( "<tr> <td class="tdt tdl tdr" style=" vertical-align:middle;">图片预览:</td> <td class="tdt tdl tdr" colspan="2"><div style="text-align:center;"><img src="project/Images/NoPhoto.jpg"/></div></td> </tr>");
htmstr.push( "</table>")
htmstr.push( "</form>");
obj.html(htmstr.join(""));
}
function fileloadon() {
$("#msg").html("");
$("img").attr({ "src": "project/Images/processing.gif" });
$("#_fileForm").submit(function () {
$("#_fileForm").ajaxSubmit({
type: "post",
url: "project/help.aspx",
success: function (data1) {
var remsg = data1.split("|");
var name = remsg[1].split("/");
if (remsg[0] == "1") {
var type = name[4].substring(name[4].indexOf("."), name[4].length);
$("#msg").html("文件名:" + name[name.length - 1] + " --- " + remsg[2]);
switch (type) {
case ".jpg":
case ".jpeg":
case ".gif":
case ".bmp":
case ".png":
$("img").attr({ "src": remsg[1] });
break;
default:
$("img").attr({ "src": "project/Images/msg_ok.png" });
break;
}
} else {
$("#msg").html("文件上传失败:" + remsg[2]);
$("img").attr({ "src": "project/Images/msg_error.png" });
}
},
error: function (msg) {
alert("文件上传失败");
}
});
return false;
});
$("#_fileForm").submit();
}
3、服务端处理上传。
protected void Page_Load(object sender, EventArgs e)
{
try
{
HttpPostedFile postFile = Request.Files[0];
//开始上传
string _savedFileResult = UpLoadFile(postFile);
Response.Write(_savedFileResult);
}
catch(Exception ex)
{
Response.Write("0|error|上传提交出错");
}
}
public string UpLoadFile(HttpPostedFile str)
{
return UpLoadFile(str, "/UpLoadFile/");
}
public string UpLoadFile(HttpPostedFile httpFile, string toFilePath)
{
try
{
//获取要保存的文件信息
string filerealname = httpFile.FileName;
//获得文件扩展名
string fileNameExt = System.IO.Path.GetExtension(filerealname);
if (CheckFileExt(fileNameExt))
{
//检查保存的路径 是否有/结尾
if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";
//按日期归类保存
string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
if (true)
{
toFilePath += datePath;
}
//物理完整路径
string toFileFullPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + toFilePath;
//检查是否有该路径 没有就创建
if (!System.IO.Directory.Exists(toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}
//得到服务器文件保存路径
string toFile = Server.MapPath("~" + toFilePath);
string f_file = getName(filerealname);
//将文件保存至服务器
httpFile.SaveAs(toFile + f_file);
return "1|" + toFilePath + f_file + "|" + "文件上传成功";
}
else
{
return "0|errorfile|" + "文件不合法";
}
}
catch (Exception e)
{
return "0|errorfile|" + "文件上传失败,错误原因:" + e.Message;
}
}
/// <summary>
/// 获取文件名
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
private string getName(string fileNamePath)
{
string[] name = fileNamePath.Split('\');
return name[name.Length - 1];
}
/// <summary>
/// 检查是否为合法的上传文件
/// </summary>
/// <param name="_fileExt"></param>
/// <returns></returns>
private bool CheckFileExt(string _fileExt)
{
string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".rar",".png" };
for (int i = 0; i < allowExt.Length; i++)
{
if (allowExt[i] == _fileExt) { return true; }
}
return false;
}
public static string GetFileName()
{
Random rd = new Random();
StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("HHmmss"));
serial.Append(rd.Next(100, 999).ToString());
return serial.ToString();
}
4、运行defualt.aspx页面以后显示的效果是:
⑦ 使用jquery.form.js实现文件上传及进度条前端代码
ajax的表单提交只能提交data数据到后台,没法实现file文件的上传还有展示进度功能,这里用到form.js的插件来实现,搭配css样式简单易上手,而且高大上,推荐使用。
需要解释下我的结构, #upload-input-file 的input标签是真实的文件上传按钮,包裹form标签后可以实现上传功能, #upload-input-btn 的button标签是展示给用户的按钮,因为需要样式的美化。上传完成生成的文件名将会显示在 .upload-file-result 里面, .progress 是进度条的位置,先让他隐藏加上 hidden 的class, .progress-bar 是进度条的主体, .progress-bar-status 是进度条的文本提醒。
去掉hidden的class,看到的效果是这样的
[图片上传失败...(image-2c700a-1548557865446)]
将上传事件绑定在file的input里面,绑定方式就随意了。
var progress = $(".progress-bar"), status = $(".progress-bar-status"), percentVal = '0%'; //上传步骤 $("#myupload").ajaxSubmit({ url: uploadUrl, type: "POST", dataType: 'json', beforeSend: function () { $(".progress").removeClass("hidden"); progress.width(percentVal); status.html(percentVal); }, uploadProgress: function (event, position, total, percentComplete) { percentVal = percentComplete + '%'; progress.width(percentVal); status.html(percentVal); console.log(percentVal, position, total); }, success: function (result) { percentVal = '100%'; progress.width(percentVal); status.html(percentVal); //获取上传文件信息 uploadFileResult.push(result); // console.log(uploadFileResult); $(".upload-file-result").html(result.name); $("#upload-input-file").val(''); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(errorThrown); $(".upload-file-result").empty(); } });
[图片上传失败...(image-3d6ae0-1548557865446)]
[图片上传失败...(image-9f0adf-1548557865446)]
更多用法可以 参考官网