本文目錄一覽:
- 1、請高手給一個JS多文件上傳的例子(必須兼容IE)解決追加50分。請看補充。
- 2、如何從js文件上傳問題,怎麼解決
- 3、js如何上傳文件
- 4、使用jquery.form.js實現文件上傳及進度條前端代碼
- 5、幾種js實現的動態多文件上傳
- 6、原生js實現文件上傳
請高手給一個JS多文件上傳的例子(必須兼容IE)解決追加50分。請看補充。
一、Servlet實現文件上傳,需要添加第三方提供的jar包
下載地址:
1) commons-fileupload-1.2.2-bin.zip: 點擊打開鏈接
2) commons-io-2.3-bin.zip: 點擊打開鏈接
接著把這兩個jar包放到 lib文件夾下:
二:文件上傳的表單提交方式必須是POST方式,
編碼類型:enctype=”multipart/form-data”,默認是 application/x-www-form-urlencoded
比如:
form action=”FileUpLoad”enctype=”multipart/form-data”method=”post”
三、舉例:
1.fileupload.jsp
%@ page language=”java” import=”javautil*” pageEncoding=”UTF-8″%
%
String path = requestgetContextPath();
String basePath = requestgetScheme()+”://”+requestgetServerName()+”:”+requestgetServerPort()+path+”/”;
%
!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 01 Transitional//EN”
html
head
base href=”%=basePath%”
titleMy JSP ‘fileuploadjsp’ starting page/title
meta http-equiv=”pragma” content=”no-cache”
meta http-equiv=”cache-control” content=”no-cache”
meta http-equiv=”expires” content=”0″
meta http-equiv=”keywords” content=”keyword1,keyword2,keyword3″
meta http-equiv=”description” content=”This is my page”
!–
link rel=”stylesheet” type=”text/css” href=”stylescss”
—
/head
body
!– enctype 默認是 application/x-www-form-urlencoded —
form action=”FileUpLoad” enctype=”multipart/form-data” method=”post”
用戶名:input type=”text” name=”usename” br/
上傳文件:input type=”file” name=”file1″br/
上傳文件: input type=”file” name=”file2″br/
input type=”submit” value=”提交”/
/form
/body
/html
2.實際處理文件上傳的 FileUpLoad.java
package comservletfileupload;
import javaioFile;
import javaio*;
import javaioIOException;
import javaioPrintWriter;
import javautilList;
import javaxservletServletException;
import javaxservlethttpHttpServlet;
import javaxservlethttpHttpServletRequest;
import javaxservlethttpHttpServletResponse;
import orgapachecommonsfileuploadFileItem;
import orgapachecommonsfileuploadFileUploadException;
import orgapachecommonsfileuploaddiskDiskFileItemFactory;
import orgapachecommonsfileuploadservletServletFileUpload;
/**
*
* @author Administrator
* 文件上傳
* 具體步驟:
* 1)獲得磁碟文件條目工廠 DiskFileItemFactory 要導包
* 2) 利用 request 獲取 真實路徑 ,供臨時文件存儲,和 最終文件存儲 ,這兩個存儲位置可不同,也可相同
* 3)對 DiskFileItemFactory 對象設置一些 屬性
* 4)高水平的API文件上傳處理 ServletFileUpload upload = new ServletFileUpload(factory);
* 目的是調用 parseRequest(request)方法 獲得 FileItem 集合list ,
*
* 5)在 FileItem 對象中 獲取信息, 遍歷, 判斷 表單提交過來的信息 是否是 普通文本信息 另做處理
* 6)
* 第一種 用第三方 提供的 itemwrite( new File(path,filename) ); 直接寫到磁碟上
* 第二種 手動處理
*
*/
public class FileUpLoad extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestsetCharacterEncoding(“utf-8”); //設置編碼
//獲得磁碟文件條目工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//獲取文件需要上傳到的路徑
String path = requestgetRealPath(“/upload”);
//如果沒以下兩行設置的話,上傳大的 文件 會佔用 很多內存,
//設置暫時存放的 存儲室 , 這個存儲室,可以和 最終存儲文件 的目錄不同
/**
* 原理 它是先存到 暫時存儲室,然後在真正寫到 對應目錄的硬碟上,
* 按理來說 當上傳一個文件時,其實是上傳了兩份,第一個是以 tem 格式的
* 然後再將其真正寫到 對應目錄的硬碟上
*/
factorysetRepository(new File(path));
//設置 緩存的大小,當上傳文件的容量超過該緩存時,直接放到 暫時存儲室
factorysetSizeThreshold(1024*1024) ;
//高水平的API文件上傳處理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//可以上傳多個文件
ListFileItem list = (ListFileItem)uploadparseRequest(request);
for(FileItem item : list)
{
//獲取表單的屬性名字
String name = itemgetFieldName();
//如果獲取的 表單信息是普通的 文本 信息
if(itemisFormField())
{
//獲取用戶具體輸入的字元串 ,名字起得挺好,因為表單提交過來的是 字元串類型的
String value = itemgetString() ;
requestsetAttribute(name, value);
}
//對傳入的非 簡單的字元串進行處理 ,比如說二進位的 圖片,電影這些
else
{
/**
* 以下三步,主要獲取 上傳文件的名字
*/
//獲取路徑名
String value = itemgetName() ;
//索引到最後一個反斜杠
int start = valuelastIndexOf(“\\”);
//截取 上傳文件的 字元串名字,加1是 去掉反斜杠,
String filename = valuesubstring(start+1);
requestsetAttribute(name, filename);
//真正寫到磁碟上
//它拋出的異常 用exception 捕捉
//itemwrite( new File(path,filename) );//第三方提供的
//手動寫的
OutputStream out = new FileOutputStream(new File(path,filename));
InputStream in = itemgetInputStream() ;
int length = 0 ;
byte [] buf = new byte[1024] ;
Systemoutprintln(“獲取上傳文件的總共的容量:”+itemgetSize());
// inread(buf) 每次讀到的數據存放在 buf 數組中
while( (length = inread(buf) ) != -1)
{
//在 buf 數組中 取出數據 寫到 (輸出流)磁碟上
outwrite(buf, 0, length);
}
inclose();
outclose();
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
//eprintStackTrace();
}
requestgetRequestDispatcher(“filedemojsp”)forward(request, response);
}
}
System.out.println(“獲取上傳文件的總共的容量:”+item.getSize());
3.filedemo.jsp
%@ page language=”java” import=”javautil*” pageEncoding=”UTF-8″%
%
String path = requestgetContextPath();
String basePath = requestgetScheme()+”://”+requestgetServerName()+”:”+requestgetServerPort()+path+”/”;
%
!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 01 Transitional//EN”
html
head
base href=”%=basePath%”
titleMy JSP ‘filedemojsp’ starting page/title
meta http-equiv=”pragma” content=”no-cache”
meta http-equiv=”cache-control” content=”no-cache”
meta http-equiv=”expires” content=”0″
meta http-equiv=”keywords” content=”keyword1,keyword2,keyword3″
meta http-equiv=”description” content=”This is my page”
!–
link rel=”stylesheet” type=”text/css” href=”stylescss”
—
/head
body
用戶名:${requestScopeusename } br/
文件:${requestScopefile1 }br/
${requestScopefile2 }br/
!– 把上傳的圖片顯示出來 —
img alt=”go” src=”upload/%=(String)requestgetAttribute(“file1″)% ” /
/body
/html
4結果頁面:
以上就是本文的全部
如何從js文件上傳問題,怎麼解決
1
第一步:新建HTML文件
使用dreamweaver CS6新建一個html文件並保存到桌面,在桌面放一個文件(圖片或文本文檔),上傳測試用。如圖:
步驟閱讀
2
第二步:寫入html頁面代碼文件
在dreamweaver中輸入以下頁面代碼:
table width=”958″
tr
tdpre style=”height:2px” a href=””文件上傳/a首頁 /td
/tr
/table
h1nbsp;a href=”” class=”STYLE9″文件上傳/aspan class=”STYLE7″文件上傳/span/h1
pnbsp;/p
div style=”width:180px; height:950px; float:left; border: #55AAFF 1px solid”
p文件上傳 /p
br /
p上傳圖片/p
form action=”doUpload.jsp” method=”post” name=”form1″ enctype=”multipart/form-data”
!– 類型enctype用multipart/form-data,這樣可以把文件中的數據作為流式數據上傳,不管是什麼文件類型,均可上傳。–
input type=”file” name=”upfile” size=”15″
input type=”submit” value=”確定”
/form/div
注意,這段代碼請放在body標籤之類。如圖:
3
第三步:寫入css樣式代碼
在head標籤之類輸入以下樣式代碼:
style type=”text/css”
!–
.STYLE1 {color: #3399FF}
.STYLE7 { font-size: 16px;
font-weight: bold;
}
.STYLE9 {font-family: “華文彩雲”;
font-size: 48px;
color: #FF0000;
}
.STYLE11 {
font-size: 16px;
color: #FF3300;
}
—
/style
用以固定頁面樣式。如圖:
4
第四步:檢測頁面樣式
用瀏覽器打開html文件,查看頁面樣式,然後做修改調整。如圖:
5
第五步:選擇文件
點擊頁面左邊的選擇文件按鈕,選中桌面文件,然後點擊打開,在頁面上會顯示文件名稱,如圖:
6
第六步:上傳文件
點擊確定按鈕,即可將文件上傳到本地磁碟,上傳成功後自動跳轉到根目錄。如圖:
js如何上傳文件
js採用File API 來上傳文件的。
File API 由一組 JavaScript 對象以及事件構成。賦予開發人員操作在 input type=」file」 … / 文件選擇控制項中選定文件的能力。圖 1 展示了 File API 所有的 JavaScript 的組合關係。
File API 簡單示例
body
h1File API Demo/h1
p
!– 用於文件上傳的表單元素 —
form name=”demoForm” id=”demoForm” method=”post” enctype=”multipart/form-data”
action=”javascript: uploadAndSubmit();”
pUpload File: input type=”file” name=”file” //p
pinput type=”submit” value=”Submit” //p
/form
divProgessing (in Bytes): span id=”bytesRead”
/span / span id=”bytesTotal”/span
/div
/p
/body
運行效果:
使用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)]
更多用法可以 參考官網
幾種js實現的動態多文件上傳
方式一:事先寫好多個input.在點擊時才顯示。也就是說上傳的最大個數是寫死了的。
html
p
a href=’#’ onclick=’javascript:viewnone(more1)’ 添加附件 /a
div id=’more1′ style=’display:none’
input type=”file” name=”attach1″ size=”50″javascript:viewnone(more2)
/span
/div
div id=’more2′ style=’display:none’
input type=”file” name=”attach2″ size=”50″‘
/div
/p
js
SCRIPT language=”javascript”
function viewnone(e){
e.style.display=(e.style.display==”none”)?””:”none”;
}
/script
方式二:這種方式的動態多文件上傳是實現了的,很簡單的,不說廢話看code
html
input type=”button” name=”button” value=”添加附件” onclick=”addInput()”
input type=”button” name=”button” value=”刪除附件” onclick=”deleteInput()”
span id=”upload”/span
js
script type=”text/javascript”
var attachname = “attach”;
var i=1;
function addInput(){
if(i0){
var attach = attachname + i ;
if(createInput(attach))
i=i+1;
}
}
function deleteInput(){
if(i1){
i=i-1;
if(!removeInput())
i=i+1;
}
}
function createInput(nm){
var aElement=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)
return false;
return true;
}
function removeInput(nm){
var aElement = document.getElementById(“upload”);
if(aElement.removeChild(aElement.lastChild) == null)
return false;
return true;
}
/script
方式三:動態多文件上傳,只是在oFileInput.click();這個地方,這樣做就不能上傳這個文件了,因為發現它在上傳之時就把這個input中的文件置空了。很可能是為了安全著想吧!
另外還有一點就是說,click()只有在ie中才能正常運行。
雖說這種方式最終沒能實現上傳,但還是留下來參考,看看是否有人可以真正實現上傳。
html
A href=”javascript:newUpload();”添加附件/A
TABLE width=”100%” border=”0″ cellpadding=”0″ cellspacing=”1″
TBODY id=”fileList”/TBODY
/TABLE
DIV id=”uploadFiles” style=”display:block”/DIV
js
SCRIPT language=”javascript”
//—新建上傳
function newUpload(){
var oFileList = document.getElementById(“fileList”);
var fileCount = oFileList.childNodes.length + 1;
var oFileInput = newFileInput(“upfile_” + fileCount);
if(selectFile(oFileInput)){
addFile(oFileInput);
}
}
//—-選擇文件
function selectFile(oFileInput){
var oUploadFiles = document.getElementById(“uploadFiles”);
oUploadFiles.appendChild(oFileInput);
oFileInput.focus();
oFileInput.click();//不能這樣做,可能是為了安全著想吧!
var fileValue = oFileInput.value;
if(fileValue == “”){
oUploadFiles.removeChild(oFileInput);
return false;
}
else
return true;
}
//—新建一個文件顯示列表
function addFile(oFileInput){
var oFileList = document.getElementById(“fileList”);
var fileIndex = oFileList.childNodes.length + 1;
var oTR = document.createElement(“TR”);
var oTD1 = document.createElement(“TD”);
var oTD2 = 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 = ‘A href=”javascript:removeFile(‘+ fileIndex + ‘);”刪除/A’;
oTR.appendChild(oTD1);
oTR.appendChild(oTD2);
oFileList.appendChild(oTR);
}
//—移除上傳的文件
function removeFile(fileIndex){
var oFileInput = document.getElementById(“upfile_” + fileIndex);
var oTR = document.getElementById(“file_” + fileIndex);
uploadFiles.removeChild(oFileInput);
fileList.removeChild(oTR);
}
//—創建一個file input對象並返回
function newFileInput(_name){
var oFileInput = 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 = ‘INPUT type=file id=’ + _name + ‘ name=’ + _name + ”;
//alert(oFileInput.outerHTML);
return oFileInput;
}
/SCRIPT
原生js實現文件上傳
function saveUser() {
var file = document.getElementById(“file”).files[0];
//原生ajax實現文件上傳
var formData = new FormData();
if (file) {
formData.append(“file”, file);
console.log(file)
}
//得到xhr對象
var xhr = null;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject(“Microsoft.XMLHTTP”);
}
xhr.open(“post”, “”, true);//設置提交方式,url,非同步提交
// xhr.setRequestHeader(“Content-Type”,”multipart/form-data”);
xhr.onload = function () {
var data = xhr.responseText; //得到返回值
console.log(data);
}
xhr.send(formData);
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/306136.html