本文目錄一覽:
- 1、java上傳附件重命名時,我寫的是File file = new File(”xxxx.txt”),可如果上傳的文件不是txt格式的該怎
- 2、java上傳成功後怎麼觸發其他操作
- 3、java 上傳附件實現方法
- 4、java附件上傳功能,上傳的附件要根據時間來重命名,上傳的路徑保存在伺服器指定目錄根據年月來分的目錄里
- 5、Java中,獲得同名file的文件名稱和內容並上傳附件,請問老師怎麼實現的?
- 6、java:上傳附件功能,點擊上傳,上傳成功後還在本頁面,問附件的路徑怎麼才能保存下來不清空求解啊謝謝了
java上傳附件重命名時,我寫的是File file = new File(”xxxx.txt”),可如果上傳的文件不是txt格式的該怎
Dto inDto = WebUtils.getParamAsDto(request);
//戶型是唯一的,先判斷是否原來存在圖片,如果存在,先刪除再上傳.
String flag = inDto.getAsString(“flag”);
if(flag.equals(“hold”)){
roomTypeService.deleteByDocId(inDto);
}
BaseActionForm cForm = (BaseActionForm) form;
FormFile myFile = cForm.getFile1();
//文件真實名稱
String fileName = myFile.getFileName();
if (myFile.getFileSize() / 1024 / 1024 inDto.getAsInteger(“doc_size”)) {
setErrTipMsg(“文件大小不能超過” + inDto.getAsInteger(“doc_size”) + “M!”,
response);
return null;
}
String fileSuffix = fileName.split(“\\.”)[1];
String suffix = inDto.getAsString(“suffix”).toUpperCase();
if (!suffix.contains(fileSuffix.toUpperCase())) {
setErrTipMsg(“請上傳” + suffix + “文件類型!”, response);
java上傳成功後怎麼觸發其他操作
java get方式非同步上傳_簡述Java非同步上傳文件的三種方式 原創
2021-02-13 16:31:03
yi bbbian
碼齡4年
關注
本文為大家分享了三種Java非同步上傳文件方式,供大家參考,具體內容如下
用第三方控制項,如Flash,ActiveX等瀏覽器插件上傳。
使用隱藏的iframe模擬非同步上傳。
使用XMLHttpRequest2來實現非同步上傳。
第一種使用瀏覽器插件上傳,需要一定的底層編碼功底,在這裡我就不講了,以免誤人子弟,提出這點大家可以自行百度。
第二種使用隱藏的iframe模擬非同步上傳。為什麼在這裡說的是模擬呢?因為我們其實是將返回結果放在了一個隱藏的iframe中,所以才沒有使當前頁面跳轉,感覺就像是非同步操作一樣。
隱藏的iframe上傳文件
附件:
正在上傳…
// 上傳完成後的回調
function uploadFinished(fileName) {
addToFlist(fileName);
loading(false);
}
function addToFlist(fname) {
var temp = [“
“,
fname,
“刪除”,
“
“
];
$(“#flist”).append(temp.join(“”));
}
function loading(showloading) {
if (showloading) {
$(“#uptxt”).show();
} else {
$(“#uptxt”).hide;
}
}
這種技術有兩個關鍵的地方:
1.form會指定target,提交的結果定向返回到隱藏的ifram中。(即form的target與iframe的name屬性一致)。
2.提交完成後,iframe中頁面與主頁面通信,通知上傳結果及服務端文件信息
如何與主頁面通信呢?
我們用nodejs在接收完了文件後返回了一個window.parent.主頁面定義的方法,執行後可以得知文件上傳完成。代碼很簡單:
router.post(‘/upload2’, multipartMiddleware, function(req, res) {
var fpath = req.files.myfile.path;
var fname = fpath.substr(fpath.lastIndexOf(‘\\’) + 1);
setTimeout(function {
var ret = [“
“window.parent.uploadFinished(‘” + fname + “‘);”,
“”];
res.send(ret.join(“”));
}, 3000);
});
執行後可以打開開發人員選項,你會發現隱藏iframe中返回了伺服器的一些數據。
第三種使用XMLHttpRequest2來進行真正的非同步上傳。
還是先貼出代碼:
執行後可以打開開發人員選項,你會發現隱藏iframe中返回了伺服器的一些數據。第三種使用XMLHttpRequest2來進行真正的非同步上傳。還是先貼出代碼:
xhr level2 非同步上傳
附件:
正在上傳…
停止上傳
function upload {
// 1.準備FormData
var fd = new FormData;
fd.append(“myfile”, $(“#myfile”)[0].files[0]);
// 創建xhr對象
var xhr = new XMLHttpRequest;
// 監聽狀態,實時響應
// xhr 和 xhr.upload 都有progress事件,xhr.progress是下載進度,xhr.upload.progress是上傳進度
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var percent = Math.round(event.loaded * 100 / event.total);
console.log(‘%d%’, percent);
$(“#upprog”).text(percent);
}
};
// 傳輸開始事件
xhr.onloadstart = function(event) {
console.log(‘load start’);
$(“#upprog”).text(‘開始上傳’);
$(“#stopbtn”).one(‘click’, function { xhr.abort; $(this).hide();});
loading(true);
};
// ajax過程成功完成事件
xhr.onload = function(event) {
console.log(‘load success’);
$(“#upprog”).text(‘上傳成功’);
console.log(xhr.responseText);
var ret = JSON.parse(xhr.responseText);
addToFlist(ret.fname);
};
// ajax過程發生錯誤事件
xhr.onerror = function(event) {
console.log(‘error’);
$(“#upprog”).text(‘發生錯誤’);
};
// ajax被取消
xhr.onabort = function(event) {
console.log(‘abort’);
$(“#upprog”).text(‘操作被取消’);
};
// loadend傳輸結束,不管成功失敗都會被觸發
xhr.onloadend = function (event) {
console.log(‘load end’);
loading(false);
};
// 發起ajax請求傳送數據
xhr.open(‘POST’, ‘/upload3’, true);
xhr.send(fd);
}
function addToFlist(fname) {
var temp = [“
“,
fname,
“刪除”,
“
“
];
$(“#flist”).append(temp.join(“”));
}
function delFile(fname) {
console.log(‘to delete file: ‘ + fname);
// TODO: 請實現
}
function loading(showloading) {
if (showloading) {
$(“#uptxt”).show();
$(“#stopbtn”).show();
} else {
$(“#uptxt”).hide();
$(“#stopbtn”).hide();
}
}
代碼有點多,但是通俗易懂。使用過AJAX的人都知道,XHR對象提供了一個onreadystatechange的回調方法來監聽整個請求/響應過程。在XMLHttpRequest2級規範中又多了幾個進度事件。有以下6個事件:
1.loadstart:在接收到響應數據的第一個位元組時觸發。
2.progress:在接收響應期間持續不斷地觸發。
3.error:在請求發生錯誤時觸發。
4.abort:在因為調用abort方法而終止連接時觸發。
5.load:在接收到完整的響應數據時觸發。
6.loadend: 在通信完成或者觸發error,abort,load事件後觸發。
這次我們可以解讀代碼:當傳輸事件開始後,我們便在停止傳送按鈕上添加點擊事件,內置了abort方法可以停止傳送。若不點則會正常上傳直到傳送完畢為止。其後台代碼類似第二種方法。
三種方法各有優劣,做個簡單的小結吧。
第三方控制項交互性和可控性好,因為接近底層,其性能也是很優秀的。但是由於編寫難度大通常需要自己安裝插件,有時可能需要自己進行編寫。
隱藏的iframe方法我個人覺得是非常有思想的一個方法,iframe可以幫我們做很多事。這種方式具有廣泛的瀏覽器兼容性而且不需要安裝插件。但是它交互性差,上傳過程不可控,而且性能也是很一般的。
XHR2級的純ajax上傳,它必須要版本比較高一點的瀏覽器(ie9+)。但是它交互性特別好,可以看到上傳進度並且是可控的。
java 上傳附件實現方法
第一,jsp上傳頁面內容:
%@ page contentType=”text/html; charset=GBK” %
%@ taglib uri=”/WEB-INF/struts-html.tld” prefix=”html” %
html
head
title
jsp1
/title
/head
body bgcolor=”#ffffff”
html:form action=”myupload.do” method=”post” enctype=”multipart/form-data”
html:file property=”thisFile”/br
html:file property=”thisFile”/br
html:submit/
/html:form
/body
/html
第二,一個javabean
package upload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
public class FileInfo extends ActionForm {
private FormFile thisFile;
public FormFile getThisFile() {
return thisFile;
}
public void setThisFile(FormFile thisFile) {
this.thisFile = thisFile;
}
public ActionErrors validate(ActionMapping actionMapping,
HttpServletRequest httpServletRequest) {
/** @todo: finish this method, this is just the skeleton.*/
return null;
}
public void reset(ActionMapping actionMapping,
HttpServletRequest servletRequest) {
}
}
第三,一個action
package upload;
import java.io.*;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import org.apache.struts.upload.FormFile;
public class myupload extends Action {
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response) throws
FileNotFoundException, IOException {
FileInfo fileInfo = (FileInfo) actionForm;
//獲取上傳文件
FormFile f=fileInfo.getThisFile();
InputStream is=f.getInputStream();
//將文件存入伺服器上
String filename=request.getSession().getServletContext().getRealPath(“/shangchuan/”+f.getFileName());
OutputStream os=new FileOutputStream(filename);
int x=0;
//優化流處理過程
byte[] buffer = new byte[8192];
while((x=is.read(buffer, 0, 8192))!=-1)
{
os.write(buffer,0,x);
}
os.close();
response.sendRedirect(“jsp1.jsp”);//根據實際情況跳轉
return null;
}
}
java附件上傳功能,上傳的附件要根據時間來重命名,上傳的路徑保存在伺服器指定目錄根據年月來分的目錄里
如果使用框架的話,比如 struts ,就比較簡單了
獲取上傳的時間:
Calendar cal = Calendar.getInstance();
String year = String.valueOf(cal.get(Calendar.YEAR));
String month = String.valueOf(cal.get(Calendar.MONTH));
獲取路徑:
String path = ServletActionContext.getServletContext().getRealPath(“/”+year+”/”+month);
直接保存在 path 這個目錄裡面就可以
如果沒有使用 框架,可以使用 FileUpload 這個 jar 包來上傳文件
Java中,獲得同名file的文件名稱和內容並上傳附件,請問老師怎麼實現的?
這個你可以這樣實現,你在頁面寫一個input type=”hidden” name=”files” id=”files”,然後在你選擇文件的時候,每選擇一個,就把這個文件的名字加到這個files中,用,號隔開,這樣就會有一個files=filename1,filenam2,filename3,filename4 這樣你在後台獲取files,然後用,號分割,就可以獲取每個附件了
多個附件上傳就是這樣做的
java:上傳附件功能,點擊上傳,上傳成功後還在本頁面,問附件的路徑怎麼才能保存下來不清空求解啊謝謝了
您好,這樣:第一,jsp上傳頁面內容:
%@ page contentType=”text/html; charset=GBK” %
%@ taglib uri=”/WEB-INF/struts-html.tld” prefix=”html” %
html
head
title
jsp1
/title
/head
body bgcolor=”#ffffff”
html:form action=”myupload.do” method=”post” enctype=”multipart/form-data”
html:file property=”thisFile”/br
html:file property=”thisFile”/br
html:submit/
/html:form
/body
/html
第二,一個javabean
package upload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
public class FileInfo extends ActionForm {
private FormFile thisFile;
public FormFile getThisFile() {
return thisFile;
}
public void setThisFile(FormFile thisFile) {
this.thisFile = thisFile;
}
public ActionErrors validate(ActionMapping actionMapping,
HttpServletRequest httpServletRequest) {
/** @todo: finish this method, this is just the skeleton.*/
return null;
}
public void reset(ActionMapping actionMapping,
HttpServletRequest servletRequest) {
}
}
第三,一個action
package upload;
import java.io.*;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import org.apache.struts.upload.FormFile;
public class myupload extends Action {
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response) throws
FileNotFoundException, IOException {
FileInfo fileInfo = (FileInfo) actionForm;
//獲取上傳文件
FormFile f=fileInfo.getThisFile();
InputStream is=f.getInputStream();
//將文件存入伺服器上
String filename=request.getSession().getServletContext().getRealPath(“/shangchuan/”+f.getFileName());
OutputStream os=new FileOutputStream(filename);
int x=0;
//優化流處理過程
byte[] buffer = new byte[8192];
while((x=is.read(buffer, 0, 8192))!=-1)
{
os.write(buffer,0,x);
}
os.close();
response.sendRedirect(“jsp1.jsp”);//根據實際情況跳轉
return null;
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/246869.html