當前位置:首頁 » 網頁前端 » 前端js如何將畫圖上傳
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

前端js如何將畫圖上傳

發布時間: 2022-10-18 09:25:34

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-超大文件上傳-如何上傳文件-大文件上傳

可以試試這樣

  1. 前端通過 input type = "file" 接收文件

  2. 然後使用文件的 slice 的方法對文件進行分片

  3. 將每一片提交到後台依次提交到後台,提交時通過 formData 提交,添加幾個欄位

    (1). 這次上傳文件的惟一 id

    (2). 上傳的狀態,是開始,還是上傳中,還是上傳結束

    (3). 分片的位置,比如是第一片,第二片

    (4). 分片的數據

  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 前端上傳多張圖片

  1. 可以用webuploader插件,上傳成功後,服務端返回圖片地址,客戶端<img>顯示圖片

  2. 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('文件上傳成功!');