Ⅰ 如何在前端用js進行多圖片上傳
產品提了一個需求,要求在一個html中實現多行多圖片上傳,原型圖如下:
2.1 :html
html頁面由前端實現,此處增加<ul><li></li></ul>是為了配合圖片單擊放大圖片功能的實現
<ul id="ul_other">
<li><input type="file" id="file_other" class="file_input" onchange="add_file_image('other')"></li>
慧雀 </ul>
2.2 :js
var imgSrc_other=[];
var imgFile_other=[];
function add_file_image(id) {
var fileList =document.getElementById("file_"+id).files;// js 獲取文件對象
if (verificationFile(fileList[0])){
for(var i =0;i
var imgSrcI =getObjectURL(fileList[i]);
if (id=="other"){
imgSrc_other.push(imgSrcI);
if(fileList[i].size/1024 >100) { //大於100kb,進行壓縮上傳
fileResizetoFile(fileList[i],0.6,function(res){
imgFile_other.push(res);
})
}else{
imgFile_other.push(res);
}
}
addNewContent(id);
}
}
//新增圖片
function addNewContent(obj) {
//刪除原先
$("#ul_"+obj).html("");
//判斷循環新增
var text="";
if (obj=="other"){
for(var a =0;a < imgSrc_examReportCard.length;a++) {
text +='<li><input type="file" id="file_other" class="file_input" onchange="add_file_image('other')"></li>';
}
}else{
console.log('臟數據');
}
var oldBox ="<li><div class=\"filediv\"><span>+</span>\n" +
"<input type=\"file\" id=\"file_"+obj+"\" class=\"file_input\" onchange=\"add_file_image('"+obj+"')\">\n" +
猜碧祥 "</div></li>";
$("#ul_"+obj).html( text+localText);
}
使用formData上傳
var form =document.getElementById("form_addArchive");//表單id
var formData =new FormData(form);
$.each(imgFile_other,function(i, file){
formData.append('imgFileOther', file);
});
$.ajax({
url:url,
type:'POST',
async:true,
cache:false,
contentType:false,
processData:false,
dataType:'json',
data:formData,
xhrFields:{
withCredentials:true
穗搏 },
success:function(data) {
}
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
}
})
後台使用@RequestParam(value ="imgFileOther", required=false) List<MultipartFile> imgFileOther, 接受
//獲取圖片url以便顯示
//文件格式驗證
//圖片壓縮
Ⅱ 怎樣用js或者jq實現點擊這個圖片就可以選擇上傳還有預覽圖片啊
<! html>
<html>
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script src="jquery-3.1.1.min.js"></script>
</head>
<body>
<h3>請選擇圖片文件:JPG/GIF</h3>
<form name="form0" id="form0" >
<input type="file" name="file0" id="file0" multiple="multiple" />
<br><br><img src="" id="img0" width="120">
</form>
</body>
<script>
$("#file0").change(function(){
var objUrl = getObjectURL(this.files[0]) ;
console.log("objUrl = "+objUrl) ;
if (objUrl)
{
$("#img0").attr("src", objUrl);
$("#img0").removeClass("hide");
}
}) ;
//建立一個可存取到該file的url
function getObjectURL(file)
{
var url = null ;
if (window.createObjectURL!=undefined)
{ // basic
url = window.createObjectURL(file) ;
}
else if (window.URL!=undefined)
{
// mozilla(firefox)
url = window.URL.createObjectURL(file) ;
}
else if (window.webkitURL!=undefined) {
// webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
$('input').on('change',function(){
var value = $(this).val();
value = value.split("\\")[2];
alert(value);
})
</script>
</html>
Ⅲ javascript對用戶上傳的圖片進行處理
這個對javascript來說有點勉為其難了。不過你可以在伺服器端用圖像處理組件(比如ASPJpeg)來做回這樣的事。以答下是把任意大小的圖片處理成120*160的例子(ASP):
<%
Set Jpeg = Server.CreateObject("Persits.Jpeg")
Jpeg.Open Server.MapPath("原圖片的路徑及文件名")
Jpeg.Quality = 80 '圖片壓縮後的顯示質量
Jpeg.Width = 120 '壓縮後的圖片寬度
Jpeg.Height = 160 '壓縮後的圖片高度
set fso=server.createobject("scripting.filesystemobject")
Jpeg.Save Server.MapPath("處理後的圖片路徑及文件名")
Jpeg.Close
Set Jpeg = Nothing
%>
通過這個你就可以對用戶上傳的圖片進行尺寸調整,具體多大的尺寸可以使圖片的位元組數控制在65K內就你自己去試了。
PS:目前大部分的WEB伺服器都支持ASPJpeg組件的。
Ⅳ 用js、jquery如何實現上傳圖片的預覽
$("#btnLoadPhoto").upload({ url: "../UploadForms/RequestUpload.aspx?action=photo", type: "json", callback: calla });
//獲得表單元素
HttpPostedFile oFile = context.Request.Files[0];
//設置上傳路徑
string strUploadPath = "temp/";
//獲取文件名稱
string fileName = context.Request.Files[0].FileName;
補充:JQuery是繼prototype之後又一個優秀的Javascript庫。它是輕量級的js庫 ,它兼容CSS3,還兼容各種瀏覽器(IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+),jQuery2.0及後續版本將不再支持IE6/7/8瀏覽器。jQuery使用戶能更方便地處理HTML(標准通用標記語言下的一個應用)、events、實現動畫效果,並且方便地為網站提供AJAX交互。jQuery還有一個比較大的優勢是,它的文檔說明很全,而且各種應用也說得很詳細,同時還有許多成熟的插件可供選擇。jQuery能夠使用戶的html頁面保持代碼和html內容分離,也就是說,不用再在html裡面插入一堆js來調用命令了,只需要定義id即可。
Ⅳ js input file文件上傳圖片並展示
1 頁面HTML內容
2 獲取input[file]元素
3 對獲取的file元素操作,也就枯蔽是操作fileReader屬性
1:Blob
2: File
3: FileList
4: FileReader
FileList :
這里,默認狀態下選擇文件 每次files屬性上FileList對象里只有一個file文件。
file對象中包含了name 文件名; size ; type 文件類型; lastModified 最後修改時間;
FileReader:非同步讀取本地文件內容;包括File 和Blob ;
創建FileReader對象;讀取file文件
關於fileReader的幾個屬性:
FileReader.error 只讀一芹橋個 DOMException 代表在讀取文件中出現的錯誤。 FileReader.readyState 只沒首州讀一個數字表明的狀態FileReader。這是以下之一:
FileReader.result 只讀文件的內容。該屬性僅在讀取操作完成後才有效,並且數據的格式取決於使用哪種方法來啟動讀取操作。
fileReader的幾個事件處理程序:
1 . FileReader.onbort:在讀取操作中止時觸發。
2 . FileReader.onerror:在讀取操作遇到錯誤時觸發。
3 . FileReader.onload:在讀取操作成功完成時觸發。
4 . FileReader.onloadstart:在開始閱讀時觸發。
5 . FileReader.onloadend:無論是否成功 只要讀取操作完成都會觸發。
6 . FileReader.onprogress:閱讀Blob內容時觸發。
FileReader的方法:
1 . FileReader.abort();中止讀取操作
2 . FileReader.readAsArrayBuffer();完成時result屬性包含ArrayBuffer表示文件數據
3 . FileReader.readAsBinaryString();完成時result屬性將包含來自文件的原始二進制數據作為字元串。
4 . FileReader.readAsDataURL();完成時result屬性包含data:表示文本數據的URL;
5 . FileReader.readAsText();完成時result屬性包含文本的內容作為文本字元串。
Ⅵ 怎麼用jquery或者javascript實現:如圖1的那個按鈕,可以讓上傳或預覽圖片
1、點擊圖1的那個按鈕可以讓用戶選擇上傳的圖片,選擇了一張就在按鈕前版面預覽,如果用權戶不想上傳某張圖片可以點擊x取消,再點擊上傳按鈕可以接著選擇圖片上傳。
2、設置選擇圖片的按鈕的 click 事件,去觸發 #upload_file 的 click 事件,然後就可以點擊圖片按鈕後,選擇本地圖片文件了。
3、設置上傳按鈕,其實一般手機版網頁是沒有上傳按鈕的,即選擇圖片後就通過 Ajax 上傳圖片了。
Ⅶ 用js腳本,怎麼實現彈出選擇圖片的對話框,並將文件上傳到伺服器
彈出抄框用框架(layer.js,具體使用可參襲考官方文檔)。
HTML如下:
!!! 注意這種提交會刷新頁面
<formname="upload-file"method="post"enctype="multipart/form-data">
<labelfor="upload-file">上傳</label>
<inputid="upload-file"type="file"name="images"hidden="hidden">
<inputtype="submit"value="提交">
</form>
提交過後後端就可以獲取到圖片(PHP獲取代碼如下:$_POST['images'];)
Ⅷ java web開發,上傳圖片並讀取
java web開發中,使用文件操作類來上傳圖片並讀取,如下代碼:
*@desc:圖片處理工具
*@author:bingye
*@createTime:2015-3-17下午04:25:32
*@version:v1.0
*/
publicclassImageUtil{
/**
*將圖片寫到客戶端
*@author:bingye
*@createTime:2015-3-17下午04:36:04
*@history:
*@paramimage
*@paramresponsevoid
*/
publicstaticvoidwriteImage(byte[]image,HttpServletResponseresponse){
if(image==null){
return;
}
byte[]buffer=newbyte[1024];
InputStreamis=null;
OutputStreamos=null;
try{
is=newByteArrayInputStream(image);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(is!=null){is.close();}
if(os!=null){os.close();}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
/**
*獲取指定路勁圖片
*@author:bingye
*@createTime:2015-3-21上午10:50:44
*@paramfilePath
*@paramresponsevoid
*/
publicstaticvoidwriteImage(StringfilePath,HttpServletResponseresponse){
FileimageFile=newFile(filePath);
if(imageFile!=null&&imageFile.exists()){
byte[]buffer=newbyte[1024];
InputStreamis=null;
OutputStreamos=null;
try{
is=newFileInputStream(imageFile);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(is!=null){is.close();}
if(os!=null){os.close();}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
/**
*圖片上傳到文件夾
*@author:bingye
*@createTime:2015-3-20下午08:07:25
*@paramfile
*@paramsavePath
*@returnboolean
*/
(CommonsMultipartFilefile,StringsavePath){
if(file!=null&&!file.isEmpty()){
//獲取文件名稱
StringfileName=file.getOriginalFilename();
//獲取後綴名
StringsuffixName=fileName.substring(fileName.indexOf(".")+1);
//新名稱
StringnewFileName=System.currentTimeMillis()+"."+suffixName;
//新文件路勁
StringfilePath=savePath+newFileName;
//獲取存儲文件路徑
FilefileDir=newFile(savePath);
if(!fileDir.exists()){
//如果文件夾沒有:新建
fileDir.mkdirs();
}
FileOutputStreamfos=null;
try{
fos=newFileOutputStream(filePath);
fos.write(file.getBytes());
fos.flush();
returnResultUtil.success("UPLOAD_SUCCESS",URLEncoder.encode(newFileName,"utf-8"));
}catch(Exceptione){
e.printStackTrace();
returnResultUtil.fail("UPLOAD_ERROR");
}finally{
try{
if(fos!=null){
fos.close();
}
}catch(IOExceptione){
e.printStackTrace();
returnResultUtil.fail("UPLOAD_ERROR");
}
}
}
returnResultUtil.fail("UPLOAD_ERROR");
}}
Ⅸ 用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")
%>
Ⅹ 如何用javascript實現<img>控制項的圖片上傳
fileupload(前台id:fleupld)控制項加一個onclick方法:getvalue()
{document.getelementbyid("label的id").innerhtml=document.getelementbyid("fleupld").value;}
document.getelementbyid("fleupld").value
獲取的是fileupload中文件的全路徑,當然你可以截取這版個值,獲得其子字元串(單權個文件的名稱)。