A. 怎么在js 里面限制上传图片的大小不能超过 1M
这样设置的:
1、先用form标签创建一个上传的表单。
<formid="form1"name="form1"method="post"action=""enctype="multipart/form-data">
<p><inputtype="hidden"name="MAX_FILE_SIZE"value="100000"/></p>
<p><inputname="userfile"id="userfile"type="file"onchange="check()"/></p>
</form>
2、用Javascript设置格式和大小。
<scriptlanguage="JavaScript"type="text/javascript">functioncheck(){varaa=document.getElementById("userfile").value.toLowerCase().split('.');//以“.”分隔上传文件字符串//varaa=document.form1.userfile.value.toLowerCase().split('.');//以“.”分隔上传文件字符串if(document.form1.userfile.value==""){alert('图片不能为空!');returnfalse;}else{if(aa[aa.length-1]=='gif'||aa[aa.length-1]=='jpg'||aa[aa.length-1]=='bmp'
||aa[aa.length-1]=='png'||aa[aa.length-1]=='jpeg')//判断图片格式{varimagSize=document.getElementById("userfile").files[0].size;alert("图片大小:"+imagSize+"B")if(imagSize<1024*1024*1)alert("图片大小在1M以内,为:"+imagSize/(1024*1024)+"M");returntrue;}else{alert('请选择格式为*.jpg、*.gif、*.bmp、*.png、*.jpeg的图片');//returnfalse;}}}</script>
图片超过1M则不能上传 如图:
B. 前端,js实现图片上传的原理是设么能回答面试即可
H5的话,就是把本地的图片按照指定的格式读取到缓存里,再供JS代码进行调用传给后台,格式的话base64吧
C. 我是前端开发的小白,这次有会js的大神吗,就是我自己写了一个图片上传的功能,支持最新浏览器,但是不
webupload 用插件吧
ie 8 9不支持 h5 新特性关于图片那段的,所以一般你想兼容ie低版本 你还是用插件吧 你自己写的那段肯定是用的h5新特性
D. JS-超大文件上传-如何上传文件-大文件上传
可以试试这样
前端通过 input type = "file" 接收文件
然后使用文件的 slice 的方法对文件进行分片
将每一片提交到后台依次提交到后台,提交时通过 formData 提交,添加几个字段
(1). 这次上传文件的惟一 id
(2). 上传的状态,是开始,还是上传中,还是上传结束
(3). 分片的位置,比如是第一片,第二片
(4). 分片的数据
后端当接收到一个文件 id 的结束标识时,把对应的分片按位置数据拼接起来就行
E. 用html, css, javascript ,怎么让用户要么选择上传自己的图片,要不选择在网页出给出的图片详情见下
可以给文件上传控件再添加一个onclick事件啊,当点击这个input时,把myimg的src赋值给cusInput,然后当onchange事件发生再把上传后的图片地址赋值给cusInput,这样的话即使因为图片路径相同未触发onchange事件,但onclick事件仍然发生了啊,cusInput仍然保留了上一次上传的图片路径:
<inputtype="file"name="pic"onchange="change(event)"onclick="cusInput=document.getElementById('myimg').src">
F. 如何使用 NodeJS 将文件或图像上传到服务器
下面先介绍上传文件到服务器(多文件上传):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GB2312";
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置允许用户上传文件大小,单位:字节,这里设为2m
fu.setSizeMax(2*1024*1024);
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath("c://windows//temp");
//开始读取上传信息
List fileItems = fu.parseRequest(request);
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();
//正则匹配,过滤路径取文件名
String regExp=".+////(.+)$";
//过滤掉的文件类型
String[] errorType={".exe",".com",".cgi",".asp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;temp<ERRORTYPE.LENGTH;TEMP++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type");
}
}
try{
//保存上传的文件到指定的目录
//在下文中上传文件至数据库时,将对这里改写
item.write(new File("d://" + m.group(1)));
out.print(name+" "+size+"");
}
catch(Exception e){
out.println(e);
}
}
else
{
throw new IOException("fail to upload");
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
}
}
现在介绍上传文件到服务器,下面只写出相关代码:
以sql2000为例,表结构如下:
字段名:name filecode
类型: varchar image
数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");
代码如下:
。。。。。。
try{
这段代码如果不去掉,将一同写入到服务器中
//item.write(new File("d://" + m.group(1)));
int byteread=0;
//读取输入流,也就是上传的文件内容
InputStream inStream=item.getInputStream();
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close();
out.println(name+" "+size+" ");
}
。。。。。。
这样就实现了上传文件至数据库
G. 用javascript写一个图片上传的功能,将图片放置在一个文件夹下
用ASP做吧!一共三个页面。再建一个名为photo.mdb数据库!' index.asp<%
Response.Buffer = True
Server.ScriptTimeOut=9999999
On Error Resume Next
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=" http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<meta content="all" name="robots" />
<meta name="author" content="mhooo,Woodeye" />
<style type="text/css">
<!--
body,input {font-size:12px;}
-->
</style>
<script language="JavaScript">
<!--
//图片按比例缩放
var flag=false;
function DrawImage(ImgD){
var image=new Image();
var iwidth = 420; //定义允许图片宽度
var iheight = 390; //定义允许图片高度
image.src=ImgD.src;
if(image.width>0 && image.height>0){
flag=true;
if(image.width/image.height>= iwidth/iheight){
if(image.width>iwidth){
ImgD.width=iwidth;
ImgD.height=(image.height*iwidth)/image.width;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt=image.width+"×"+image.height;
}
else{
if(image.height>iheight){
ImgD.height=iheight;
ImgD.width=(image.width*iheight)/image.height;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt=image.width+"×"+image.height;
}
}
}
//-->
</script>
<title></title>
</head>
<body id="body">
<div align="center">
<%
ExtName = "jpg,gif,png" '允许扩展名
SavePath = "upload" '保存路径
If Right(SavePath,1)<>"/" Then SavePath=SavePath&"/" '在目录后加(/)
CheckAndCreateFolder(SavePath) UpLoadAll_a = Request.TotalBytes '取得客户端全部内容
If(UpLoadAll_a>0) Then
Set UploadStream_c = Server.CreateObject("ADODB.Stream")
UploadStream_c.Type = 1
UploadStream_c.Open
UploadStream_c.Write Request.BinaryRead(UpLoadAll_a)
UploadStream_c.Position = 0 FormDataAll_d = UploadStream_c.Read
CrLf_e = chrB(13)&chrB(10)
FormStart_f = InStrB(FormDataAll_d,CrLf_e)
FormEnd_g = InStrB(FormStart_f+1,FormDataAll_d,CrLf_e) Set FormStream_h = Server.Createobject("ADODB.Stream")
FormStream_h.Type = 1
FormStream_h.Open
UploadStream_c.Position = FormStart_f + 1
UploadStream_c.CopyTo FormStream_h,FormEnd_g-FormStart_f-3
FormStream_h.Position = 0
FormStream_h.Type = 2
FormStream_h.CharSet = "GB2312"
FormStreamText_i = FormStream_h.Readtext
FormStream_h.Close FileName_j = Mid(FormStreamText_i,InstrRev(FormStreamText_i,"\")+1,FormEnd_g) If(CheckFileExt(FileName_j,ExtName)) Then
SaveFile = Server.MapPath(SavePath & FileName_j) If Err Then
Response.Write "文件上传: <span style=""color:red;"">文件上传出错!</span> <a href=""" & Request.ServerVariables("URL") &""">重新上传文件</a>
"
Err.Clear
Else
SaveFile = CheckFileExists(SaveFile) k=Instrb(FormDataAll_d,CrLf_e&CrLf_e)+4
l=Instrb(k+1,FormDataAll_d,leftB(FormDataAll_d,FormStart_f-1))-k-2
FormStream_h.Type=1
FormStream_h.Open
UploadStream_c.Position=k-1
UploadStream_c.CopyTo FormStream_h,l
FormStream_h.SaveToFile SaveFile,2 SaveFileName = Mid(SaveFile,InstrRev(SaveFile,"\")+1)
Response.write "文件上传: <img src=../img.asp?src=" & SaveFileName & " onload ='DrawImage(this)'/> 文件上传成功! <a href=""" & Request.ServerVariables("URL") &""">继续上传文件</a><p><span style=""color:red;"">(申请将图片显示在网站首页!)</span> <form action='a.asp' method='post'><input name='pic' type='hidden' value='" & SaveFileName & "' /><input type='submit' name='Submit' value='点击申请' style='height:18px;border:1px solid #CCCCCC'/></form>"
End If
Else
Response.write "文件上传: <span style=""color:red;"">文件格式不正确!</span> <a href=""" & Request.ServerVariables("URL") &""">重新上传文件</a>
"
End If Else
%>
<script language="Javascript">
<!--
function ValidInput()
{ if(document.upform.upfile.value=="")
{
alert("请选择上传文件!")
document.upform.upfile.focus()
return false
}
return true
}
// -->
</script>
</div>
<form action='<%= Request.ServerVariables("URL") %>' method='post' name="upform" onsubmit="return ValidInput()" enctype="multipart/form-data">
文件上传:
<input type='file' name='upfile' size="40" style="height:18px;border:1px solid #CCCCCC" > <input type='submit' value="上传" style="height:18px;border:1px solid #CCCCCC">
</form>
<%
End if
Set FormStream_h = Nothing
UploadStream.Close
Set UploadStream = Nothing
%>
</body>
</html>
<%
'判断文件类型是否合格
Function CheckFileExt(FileName,ExtName) '文件名,允许上传文件类型
FileType = ExtName
FileType = Split(FileType,",")
For i = 0 To Ubound(FileType)
If LCase(Right(FileName,3)) = LCase(FileType(i)) then
CheckFileExt = True
Exit Function
Else
CheckFileExt = False
End if
Next
End Function '检查上传文件夹是否存在,不存在则创建文件夹
Function CheckAndCreateFolder(FolderName)
fldr = Server.Mappath(FolderName)
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(fldr) Then
fso.CreateFolder(fldr)
End If
Set fso = Nothing
End Function '检查文件是否存在,重命名存在文件
Function CheckFileExists(FileName)
Set fso=Server.CreateObject("Scripting.FileSystemObject")
If fso.FileExists(SaveFile) Then
i=1
msg=True
Do While msg
CheckFileExists = Replace(SaveFile,Right(SaveFile,4),"_" & i & Right(SaveFile,4))
If not fso.FileExists(CheckFileExists) Then
msg=False
End If
i=i+1
Loop
Else
CheckFileExists = FileName
End If
Set fso=Nothing
End Function
%> ' a.asp<!--#include file="conn.asp" -->
<%
pic=request.form("pic")
exec="insert into guest(pic)values('"+pic+"')"
conn.execute exec
conn.close
set conn=nothing
Response.Write("<script language=javascript>alert('恭喜您,申请成功!您上传的图片将在本站首页显示!')</script>")
response.write("<script>window.opener=null;window.close();</script>")
%>
'conn.asp<%
set conn=server.createobject("adodb.connection")
conn.open "driver={microsoft access driver (*.mdb)};dbq="&server.mappath("data/photo.mdb")
%>
H. JS中如何把上传的图片保存到指定文件目录
用JSPSMART处理,参考下面代码实现
<%
//程序初始化 下面设置成要保存的文件夹
String path_tmp = request.getRealPath("/") + "Upload";
String filename_p = "Test";
String path_new = request.getRealPath("/") + "Upload\\" + filename_p;
//文件上传
SmartUpload su = new SmartUpload();
su.initialize(pageContext);
su.upload();
int count = su.save(path_tmp);
//参数提取,后面贴不了,说我的重复内容多,这玩意真差...
%>
I. js 前端上传多张图片
可以用webuploader插件,上传成功后,服务端返回图片地址,客户端<img>显示图片
X关闭按钮这个得自己用css样式控制,点击X后,服务端删除图片,然后前端移除该X掉的图片
J. 我想实现 html +js 上传图片 并保存到本地tmp目录下,现有代码如下,求指导。必采纳
你js代码把文件以base64编码形式展示了出来,是为了让用户上传文件之前能够预览对吧。
文件的IO操作需要用后端来实现,如果你只是做web前端开发的话,就没有必要研究这个东西,如果你是后端开发者的话可以尝试一下,相关的资料很多,我写个示例吧,后端用php为例:
html实现:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<title>ss</title>
</head>
<body>
<formaction="file.php"method="post"enctype="multipart/form-data">
<inputtype="file"name="upfile">
<inputtype="submit"value="提交">
</form>
</body>
</html>
php实现(file.php):
<?php
@header('Content-Type:text/html;charset=utf-8');
if(!isset($_FILES['upfile'])){
exit('请选择您要上传的文件!');
}
if(!file_exists($_FILES['upfile']['tmp_name'])){
exit('您要上传的文件不存在!');
}
$file_dir=dirname(__FILE__).'/tmp';
if(!is_file($file_dir)){
@mkdir($file_dir,0777,true);
}
$file_ext='.jpg';
if(preg_match('/(.w+)$/',$_FILES['upfile']['name'],$ext_tmp)){
$file_ext=$ext_tmp[1];
}
$file_save_path=$file_dir.'/'.uniqid().mt_rand(101,999).$file_ext;
@rename($_FILES['upfile']['tmp_name'],$file_save_path);
if(!file_exists($file_save_path)){
exit('文件上传失败!');
}
exit('文件上传成功!');