本文目錄一覽:
- 1、jsp 大文件分片上傳處理如何實現?
- 2、jsp 如何實現文件上傳和下載功能?
- 3、java編程:怎麼用JSP(javabean)上傳一張圖片到服務器的指定文件夾呢?
- 4、jsp文件的上傳為什麼會出現錯誤,想請教各位朋友們?
- 5、Jsp上傳文件報錯:Undefined type: org.lxh.smart.SmartUpload Java
jsp 大文件分片上傳處理如何實現?
javaweb上傳文件
上傳文件的jsp中的部分
上傳文件同樣可以使用form表單向後端發請求,也可以使用 ajax向後端發請求
1.通過form表單向後端發送請求
form id=”postForm” action=”${pageContext.request.contextPath}/UploadServlet” method=”post” enctype=”multipart/form-data”
div class=”bbxx wrap”
inputtype=”text” id=”side-profile-name” name=”username” class=”form-control”
inputtype=”file” id=”example-file-input” name=”avatar”
button type=”submit” class=”btn btn-effect-ripple btn-primary”Save/button
/div
/form
改進後的代碼不需要form標籤,直接由控件來實現。開發人員只需要關注業務邏輯即可。JS中已經幫我們封閉好了
this.post_file = function ()
{
$.each(this.ui.btn, function (i, n) { n.hide();});
this.ui.btn.stop.show();
this.State = this.Config.state.Posting;//
this.app.postFile({ id: this.fileSvr.id, pathLoc: this.fileSvr.pathLoc, pathSvr:this.fileSvr.pathSvr,lenSvr: this.fileSvr.lenSvr, fields: this.fields });
};
通過監控工具可以看到控件提交的數據,非常的清晰,調試也非常的簡單。
2.通過ajax向後端發送請求
$.ajax({
url : “${pageContext.request.contextPath}/UploadServlet”,
type : “POST”,
data : $( ‘#postForm’).serialize(),
success : function(data) {
$( ‘#serverResponse’).html(data);
},
error : function(data) {
$( ‘#serverResponse’).html(data.status + ” : ” + data.statusText + ” : ” + data.responseText);
}
});
ajax分為兩部分,一部分是初始化,文件在上傳前通過AJAX請求通知服務端進行初始化操作
this.md5_complete = function (json)
{
this.fileSvr.md5 = json.md5;
this.ui.msg.text(“MD5計算完畢,開始連接服務器…”);
this.event.md5Complete(this, json.md5);//biz event
var loc_path = encodeURIComponent(this.fileSvr.pathLoc);
var loc_len = this.fileSvr.lenLoc;
var loc_size = this.fileSvr.sizeLoc;
var param = jQuery.extend({}, this.fields, this.Config.bizData, { md5: json.md5, id: this.fileSvr.id, lenLoc: loc_len, sizeLoc: loc_size, pathLoc: loc_path, time: new Date().getTime() });
$.ajax({
type: “GET”
, dataType: ‘jsonp’
, jsonp: “callback” //自定義的jsonp回調函數名稱,默認為jQuery自動生成的隨機函數名
, url: this.Config[“UrlCreate”]
, data: param
, success: function (sv)
{
_this.svr_create(sv);
}
, error: function (req, txt, err)
{
_this.Manager.RemoveQueuePost(_this.fileSvr.id);
alert(“向服務器發送MD5信息錯誤!” + req.responseText);
_this.ui.msg.text(“向服務器發送MD5信息錯誤”);
_this.ui.btn.cancel.show();
_this.ui.btn.stop.hide();
}
, complete: function (req, sta) { req = null; }
});
};
在文件上傳完後向服務器發送通知
this.post_complete = function (json)
{
this.fileSvr.perSvr = “100%”;
this.fileSvr.complete = true;
$.each(this.ui.btn, function (i, n)
{
n.hide();
});
this.ui.process.css(“width”, “100%”);
this.ui.percent.text(“(100%)”);
this.ui.msg.text(“上傳完成”);
this.Manager.arrFilesComplete.push(this);
this.State = this.Config.state.Complete;
//從上傳列表中刪除
this.Manager.RemoveQueuePost(this.fileSvr.id);
//從未上傳列表中刪除
this.Manager.RemoveQueueWait(this.fileSvr.id);
var param = { md5: this.fileSvr.md5, uid: this.uid, id: this.fileSvr.id, time: new Date().getTime() };
$.ajax({
type: “GET”
, dataType: ‘jsonp’
, jsonp: “callback” //自定義的jsonp回調函數名稱,默認為jQuery自動生成的隨機函數名
, url: _this.Config[“UrlComplete”]
, data: param
, success: function (msg)
{
_this.event.fileComplete(_this);//觸發事件
_this.post_next();
}
, error: function (req, txt, err) { alert(“文件-向服務器發送Complete信息錯誤!” + req.responseText); }
, complete: function (req, sta) { req = null; }
});
};
這裡需要處理一個MD5秒傳的邏輯,當服務器存在相同文件時,不需要用戶再上傳,而是直接通知用戶秒傳
this.post_complete_quick = function ()
{
this.fileSvr.perSvr = “100%”;
this.fileSvr.complete = true;
this.ui.btn.stop.hide();
this.ui.process.css(“width”, “100%”);
this.ui.percent.text(“(100%)”);
this.ui.msg.text(“服務器存在相同文件,快速上傳成功。”);
this.Manager.arrFilesComplete.push(this);
this.State = this.Config.state.Complete;
//從上傳列表中刪除
this.Manager.RemoveQueuePost(this.fileSvr.id);
//從未上傳列表中刪除
this.Manager.RemoveQueueWait(this.fileSvr.id);
//添加到文件列表
this.post_next();
this.event.fileComplete(this);//觸發事件
};
這裡可以看到秒傳的邏輯是非常 簡單的,並不是特別的複雜。
var form = new FormData();
form.append(“username”,”zxj”);
form.append(“avatar”,file);
//var form = new FormData($(“#postForm”)[0]);
$.ajax({
url:”${pageContext.request.contextPath}/UploadServlet”,
type:”post”,
data:form,
processData:false,
contentType:false,
success:function(data){
console.log(data);
}
});
java部分
文件初始化的邏輯,主要代碼如下
FileInf fileSvr= new FileInf();
fileSvr.id = id;
fileSvr.fdChild = false;
fileSvr.uid = Integer.parseInt(uid);
fileSvr.nameLoc = PathTool.getName(pathLoc);
fileSvr.pathLoc = pathLoc;
fileSvr.lenLoc = Long.parseLong(lenLoc);
fileSvr.sizeLoc = sizeLoc;
fileSvr.deleted = false;
fileSvr.md5 = md5;
fileSvr.nameSvr = fileSvr.nameLoc;
//所有單個文件均以uuid/file方式存儲
PathBuilderUuid pb = new PathBuilderUuid();
fileSvr.pathSvr = pb.genFile(fileSvr.uid,fileSvr);
fileSvr.pathSvr = fileSvr.pathSvr.replace(“\\”,”/”);
DBConfig cfg = new DBConfig();
DBFile db = cfg.db();
FileInf fileExist = new FileInf();
boolean exist = db.exist_file(md5,fileExist);
//數據庫已存在相同文件,且有上傳進度,則直接使用此信息
if(exist fileExist.lenSvr 1)
{
fileSvr.nameSvr = fileExist.nameSvr;
fileSvr.pathSvr = fileExist.pathSvr;
fileSvr.perSvr = fileExist.perSvr;
fileSvr.lenSvr = fileExist.lenSvr;
fileSvr.complete = fileExist.complete;
db.Add(fileSvr);
//觸發事件
up6_biz_event.file_create_same(fileSvr);
}//此文件不存在
else
{
db.Add(fileSvr);
//觸發事件
up6_biz_event.file_create(fileSvr);
FileBlockWriter fr = new FileBlockWriter();
fr.CreateFile(fileSvr.pathSvr,fileSvr.lenLoc);
}
接收文件塊數據,在這個邏輯中我們接收文件塊數據。控件對數據進行了優化,可以方便調試。如果用監控工具可以看到控件提交的數據。
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List files = null;
try
{
files = upload.parseRequest(request);
}
catch (FileUploadException e)
{// 解析文件數據錯誤
out.println(“read file data error:” + e.toString());
return;
}
FileItem rangeFile = null;
// 得到所有上傳的文件
Iterator fileItr = files.iterator();
// 循環處理所有文件
while (fileItr.hasNext())
{
// 得到當前文件
rangeFile = (FileItem) fileItr.next();
if(StringUtils.equals( rangeFile.getFieldName(),”pathSvr”))
{
pathSvr = rangeFile.getString();
pathSvr = PathTool.url_decode(pathSvr);
}
}
boolean verify = false;
String msg = “”;
String md5Svr = “”;
long blockSizeSvr = rangeFile.getSize();
if(!StringUtils.isBlank(blockMd5))
{
md5Svr = Md5Tool.fileToMD5(rangeFile.getInputStream());
}
verify = Integer.parseInt(blockSize) == blockSizeSvr;
if(!verify)
{
msg = “block size error sizeSvr:” + blockSizeSvr + “sizeLoc:” + blockSize;
}
if(verify !StringUtils.isBlank(blockMd5))
{
verify = md5Svr.equals(blockMd5);
if(!verify) msg = “block md5 error”;
}
if(verify)
{
//保存文件塊數據
FileBlockWriter res = new FileBlockWriter();
//僅第一塊創建
if( Integer.parseInt(blockIndex)==1) res.CreateFile(pathSvr,Long.parseLong(lenLoc));
res.write( Long.parseLong(blockOffset),pathSvr,rangeFile);
up6_biz_event.file_post_block(id,Integer.parseInt(blockIndex));
JSONObject o = new JSONObject();
o.put(“msg”, “ok”);
o.put(“md5”, md5Svr);
o.put(“offset”, blockOffset);//基於文件的塊偏移位置
msg = o.toString();
}
rangeFile.delete();
out.write(msg);
jsp 如何實現文件上傳和下載功能?
上傳:
MyjspForm mf = (MyjspForm) form;// TODO Auto-generated method stub
FormFile fname=mf.getFname();
byte [] fn = fname.getFileData();
OutputStream out = new FileOutputStream(“D:\\”+fname.getFileName());
Date date = new Date();
String title = fname.getFileName();
String url = “d:\\”+fname.getFileName();
Upload ul = new Upload();
ul.setDate(date);
ul.setTitle(title);
ul.setUrl(url);
UploadDAO uld = new UploadDAO();
uld.save(ul);
out.write(fn);
out.close();
下載:
DownloadForm downloadForm = (DownloadForm)form;
String fname = request.getParameter(“furl”);
FileInputStream fi = new FileInputStream(fname);
byte[] bt = new byte[fi.available()];
fi.read(bt);
//設置文件是下載還是打開以及打開的方式msdownload表示下載;設置字湖集,//主要是解決文件中的中文信息
response.setContentType(“application/msdownload;charset=gbk”);
//文件下載後的默認保存名及打開方式
String contentDisposition = “attachment; filename=” + “java.txt”;
response.setHeader(“Content-Disposition”,contentDisposition);
//設置下載長度
response.setContentLength(bt.length);
ServletOutputStream sos = response.getOutputStream();
sos.write(bt);
return null;
java編程:怎麼用JSP(javabean)上傳一張圖片到服務器的指定文件夾呢?
先導smartupload jar包!在寫form表單input tyle=”file” enctype=”multipart/form-data” method=”post”enctype和method別寫錯了!
寫一個簡單的吧!
%page import=”com.jspsmart.upload.*”%
%
SmartUpload su=new SmartUpload ();//初始化SmartUpload對象
try{ //捕獲他可能出現的異常
su.upload();//執行上傳
}catch(Exception ex){
ex.printStackTrace;
}
File file=su.getFile().getFile(0); //(得到單個的上傳文件的信息)這裡得到的File對象是你到的jar包里的com.jspsmart.upload.File類型 別寫成IO 裏面的File了
String filepath=”upload\\”; //在這之前要在你所建項目的目錄下單建一個upload文件夾
filepath+=file.getFileName();
file.saveAs(filepath,SmartUpload.SAVE-VIRTUAL);
不知道是否建了與它相對應的數據庫表啊?
不懂得再玩吧!
%
jsp文件的上傳為什麼會出現錯誤,想請教各位朋友們?
為什麼item是空的?
原因就是因為在web.xml中配置了struts的filter
struts2
/*
改成
struts2
*.action
就可以了
struts2過濾時,會改變reqeust的類型,由httpservletrequest變成multipartrequestwrapper
所以parserequest就返回了null
Jsp上傳文件報錯:Undefined type: org.lxh.smart.SmartUpload Java
這個錯誤是由於jsp頁面導入jar包錯誤導致SmartUpload沒有找到。
應該是導入com.jspsmart.upload.SmartUpload這個類。
jspSmartUpload是一個可免費使用的全功能的文件上傳下載組件,適於嵌入執行上傳下載操作的JSP文件中。該組件有以下幾個特點:
1、使用簡單。在JSP文件中僅僅書寫三五行java代碼就可以搞定文件的上傳或下載,方便。
2、能全程控制上傳。利用jspSmartUpload組件提供的對象及其操作方法,可以獲得全部上傳文件的信息(包括文件名,大小,類型,擴展名,文件數據等),方便存取。
3、能對上傳的文件在大小、類型等方面做出限制。如此可以濾掉不符合要求的文件。
4、下載靈活。僅寫兩行代碼,就能把Web服務器變成文件服務器。不管文件在Web服務器的目錄下或在其它任何目錄下,都可以利用jspSmartUpload進行下載。
原創文章,作者:EDBBK,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/128735.html