- 1、jsp上傳文件代碼!
- 2、Jsp上傳圖片到指定文件夾下 求詳細代碼
- 3、jsp 大文件分片上傳處理如何實現?
- 4、求一段能用的jsp上傳文件的代碼
其實就是讀流的形式。我這有個struts1的,自己研究下。可以批量上傳配置文件:#路徑請用雙\
path=c:\\test\\
#大小為b
fileSize=5000
#文件類型用”,”隔開
fileType=jpg,txt主要類:// 路徑常量
public static final String FILEPATH = “path”;
// 文件大小
public static final String FILESIZE = “fileSize”;
// 文件類型
public static final String FILETYPE = “fileType”; /**
* @param key:資源文件key值
* @return 返回對應key的value
*/
public static String getValueByKey(String key) {
String rKey = “”;
CommonUtil util = new CommonUtil();
// 獲取資源文件流
InputStream in = util.getClass().getResourceAsStream(
“/upload.properties”); Properties props = new Properties();
try {
// 載入資源文件
props.load(in);
// 獲取資源文件對應key值
rKey = props.get(key).toString();
in.close();
} catch (IOException e) {
e.printStackTrace(); }
return rKey; // 遍歷所有key值
// Set set = props.keySet();
// Iterator it = set.iterator();
// System.out.println(“Begin …”);
// while(it.hasNext()){
// System.out.println((String)it.next());
// }
// System.out.println(“End”);
} /**
* 根據系統時間+兩位數字隨機數產生文件名
*
* @return 例:2010091521202315
*/
public static String getFileName() {
// 格式化日期
SimpleDateFormat s = new SimpleDateFormat(“yyyyMMddHHmmss”);
String fileName = s.format(new Date());
// 隨機數
Random r = new Random();
int random = 0;
do {
random = r.nextInt(100);
} while (random 10);
// 連接字元串
fileName += random;
return fileName;
} /**
* 上傳文件集合
*
* @param files:FormFile的集合
* @param code:數據字典模塊路徑id
* @param fileName:文件真實名稱
* @return 上傳後的文件id數組
*/
public static String[] filesUpload(List files, int code, String[] fileName)
throws IOException, Exception {
// 輸出文件名
for (int i = 0; i fileName.length; i++) {
System.out.println(“文件” + (i + 1) + “名字:” + fileName[i]);
}
// 獲取資源文件上傳路徑
String path = CommonUtil.getValueByKey(CommonUtil.FILEPATH);
System.out.println(“資源文件路徑:” + path);
// 獲取大小文件上限
long fileSize = Long.parseLong(CommonUtil
.getValueByKey(CommonUtil.FILESIZE));
System.out.println(“文件上限大小:” + fileSize + “b”);
// 獲取文件類型
String types = CommonUtil.getValueByKey(CommonUtil.FILETYPE).toString();
System.out.println(“限制文件類型:” + types);
// 數組轉為集合
List fileTypes = Arrays.asList(types.split(“,”)); // 首先遍歷文件集合判斷是否合法
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
// 單個文件
FormFile file = (FormFile) iterator.next();
// 文件類型
String ext = file.getFileName().substring(
file.getFileName().lastIndexOf(“.”) + 1,
file.getFileName().length());
// 遍歷文件類型集合進行判斷
if (!fileTypes.contains(ext)) {
throw new Exception(“不允許上傳” + ext + “類型文件”);
}
if (fileSize file.getFileSize()) {
throw new Exception(“上傳的文件過大”);
}
}
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
// 單個文件
FormFile file = (FormFile) iterator.next(); /*
* 。。。。。。。。。。。。。。。實際上傳路徑
*/
// 根據實際上傳路徑新建文件夾
new File(path).mkdirs();
// 文件輸出路徑
String savePath = path + getFileName() + “.jpg”;
System.out.println(“文件輸出路徑” + savePath);
if (file.getFileSize() 10) {
// 輸入流
InputStream input = file.getInputStream();
byte[] b = new byte[1024];
// 輸出流
FileOutputStream fileoutput = new FileOutputStream(savePath);
// 開始輸出
while (input.read(b) != -1) {
fileoutput.write(b);
}
fileoutput.close();
input.close();
// 文件上傳結束
}
}
/*
* 。。。。。。。。。。。。。。獲取上傳後的文件名
*/
return null;
}
String time = new SimpleDateFormat(“yyyyMMddHHmmss”)
.format(Calendar.getInstance().getTime());// 得到系統時間
// 上傳技術
SmartUpload up = new SmartUpload();
// 進行初始化
up.initialize(this.getServletConfig(), request, response);
// 開始上傳
try {
up.upload(“utf-8”);//設置編碼方式。
int id = Integer.parseInt(up.getRequest().getParameter(“id”));// 商品編號
SmartFiles sf = up.getFiles();// 得到上傳的所有圖片
SmartFile file = sf.getFile(0);// 根據索引得到上傳圖片 多個圖片可以用循環:
String type = file.getFileExt();// 得到圖片後綴名
String folder = “tp/”;// 指定文件夾
String path = folder + time + “.” + type;// 路徑
System.out.println(path + “路徑”);
file.saveAs(request.getRealPath(“/”) + path);// 保存圖片
} catch (Exception e) {
e.printStackTrace();
}
//你搞個郵箱我把SmartUploadjar包 發給你吧。 //設置from提交
/*form action=”SellerServet” method=”post”
enctype=”multipart/form-data”*/ // 加上 enctype=”multipart/form-data
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);
%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%
%@ page language=”java” import=”java.io.*,com.jspsmart.upload.*”%
HTMLHEAD
meta http-equiv=”Content-Type” content=”text/html”;charset=UFT-8
TITLESave upload /TITLE
/HEAD
BODY
%
// 將上傳文件全部保存到指定目錄創建文件夾使用絕對路徑
String uploadPath =request.getRealPath(“/”)+”/images/”;
java.io.File fdir = new java.io.File(uploadPath);
if(!fdir.exists()){
fdir.mkdirs();
}
SmartUpload su = new SmartUpload();
su.initialize(pageContext);
// 設定上傳限制
// 1.限制每個上傳文件的最大長度。
//su.setMaxFileSize(5120000); //5M
// 2.限制總上傳數據的長度。
//su.setTotalMaxFileSize(25600000);//5M*5
// 3.設定允許上傳的文件(通過擴展名限制)。
//su.setAllowedFilesList(“gif,jpg,png,bmp,GIF,JPG,PNG,BMP”);
// 4.設定禁止上傳的文件(通過擴展名限制),禁止上傳帶有exe,bat,
//jsp,htm,html擴展名的文件和沒有擴展名的文件。
//su.setDeniedFilesList(“exe,bat,jsp,htm,html,,”);
// 上傳文件
su.upload();
String x = su.getRequest().getParameter(“x”) ;
out.println(“table border=’1′ width=’560′”);
out.println(“tr”);
out.println(“th文件名/th”);
out.println(“th文件大小/th”);
out.println(“/tr”);
for(int i=0;isu.getFiles().getCount();i++){
com.jspsmart.upload.File file=su.getFiles().getFile(i);
if(file.isMissing()){
continue;
}
out.println(“tr”);
out.println(“td”+file.getFileName()+”/td”);
out.println(“td”+file.getSize()+”/td”);
out.println(“/tr”);
String ext=”.”+file.getFileExt();
String strtemp=uploadPath+”/”+x+ext;
file.saveAs(strtemp);
}
out.println(“/table”);
%
/body
/html
上面是完整的代碼。
原創文章,作者:OH8MK,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127030.html