当前位置:网站首页>Asp.net large file block upload breakpoint resume demo
Asp.net large file block upload breakpoint resume demo
2022-07-28 16:41:00 【51CTO】
javaweb Upload files
Of uploaded files jsp Part of
Upload files can also be used form The form sends a request back , You can also use ajax Send a request back
1. adopt form The form sends a request back
<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>
The improved code does not need form label , Directly by the control to achieve . Developers just need to focus on business logic .JS China has closed it for us
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 });
};
Through the monitoring tool, you can see the data submitted by the control , Very clear , Debugging is also very simple .
2. adopt ajax Send a request back
$.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 In two parts , Part of it is initialization , File passed before upload AJAX Request to inform the server to initialize
this.md5_complete = function (json)
{
this.fileSvr.md5 = json.md5;
this.ui.msg.text("MD5 Calculation completed , Start connecting to server ...");
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" // Self defined jsonp Callback function name , The default is jQuery Auto generated random function name
, 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(" Send to server MD5 Wrong information !" + req.responseText);
_this.ui.msg.text(" Send to server MD5 Wrong information ");
_this.ui.btn.cancel.show();
_this.ui.btn.stop.hide();
}
, complete: function (req, sta) { req = null; }
});
};
Send a notification to the server after the file is uploaded
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(" Upload to complete ");
this.Manager.arrFilesComplete.push(this);
this.State = this.Config.state.Complete;
// Delete... From the upload list
this.Manager.RemoveQueuePost(this.fileSvr.id);
// Delete from never uploaded list
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" // Self defined jsonp Callback function name , The default is jQuery Auto generated random function name
, url: _this.Config["UrlComplete"]
, data: param
, success: function (msg)
{
_this.event.fileComplete(_this);// Triggering event
_this.post_next();
}
, error: function (req, txt, err) { alert(" file - Send to server Complete Wrong information !" + req.responseText); }
, complete: function (req, sta) { req = null; }
});
};
We need to deal with a MD5 Second pass logic , When the same file exists on the server , No need for users to upload , It's a direct notification to the user
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(" The same file exists on the server , Fast upload successful .");
this.Manager.arrFilesComplete.push(this);
this.State = this.Config.state.Complete;
// Delete... From the upload list
this.Manager.RemoveQueuePost(this.fileSvr.id);
// Delete from never uploaded list
this.Manager.RemoveQueueWait(this.fileSvr.id);
// Add to file list
this.post_next();
this.event.fileComplete(this);// Triggering event
};
Here we can see that the logic of second transmission is very ordinary , It's not particularly complicated .
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 part
The logic of file initialization , The main codes are as follows
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;
// All individual documents are marked with uuid/file Way to store
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);
// The same file already exists in the database , And upload progress , Use this information directly
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);
// Triggering event
up6_biz_event.file_create_same(fileSvr);
}// This file does not exist
else
{
db.Add(fileSvr);
// Triggering event
up6_biz_event.file_create(fileSvr);
FileBlockWriter fr = new FileBlockWriter();
fr.CreateFile(fileSvr.pathSvr,fileSvr.lenLoc);
}
Receive file block data , In this logic we receive file block data . Control to optimize the data , It's easy to debug . If the monitoring tool can see the data submitted by the control .
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)
{// Error parsing file data
out.println("read file data error:" + e.toString());
return;
}
FileItem rangeFile = null;
// Get all the uploaded files
Iterator fileItr = files.iterator();
// Loop through all files
while (fileItr.hasNext())
{
// Get the current file
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)
{
// Save file block data
FileBlockWriter res = new FileBlockWriter();
// Only the first piece creates
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);// Block offset based on file
msg = o.toString();
}
rangeFile.delete();
out.write(msg);
notes :
1. above java Part of the code can be used directly , Just upload the image path and collect the data and write the data to the database
2. The above upload file uses a byte stream , In fact, you can use other streams , This requires the reader to complete the test himself below
3. BeanUtils It's a tool It is convenient to assign the corresponding attributes of the entity to the entity
4. Upload file cannot be used request.getParameter("") Got parameters , It's about putting request analysis , By judging whether each item is a document or not , Then carry out the corresponding operation ( File is read by stream , If it's not a document , Save temporarily to a map in .)
The back-end code logic is mostly the same , Can currently support MySQL,Oracle,SQL. Before use, you need to configure the database , You can refer to this article I wrote : http://blog.ncmem.com/wordpress/2019/08/12/java-http%E5%A4%A7%E6%96%87%E4%BB%B6%E6%96%AD%E7%82%B9%E7%BB%AD%E4%BC%A0%E4%B8%8A%E4%BC%A0/ Welcome to join the group to discuss “374992201”
边栏推荐
- El input limit can only input the specified number
- QT QString详解
- Rosen's QT journey 101 models and views in QT quick
- Ansa secondary development - two methods of drawing the middle surface
- About the web docking pin printer, lodop uses
- Thoughts on solving the pop-up of malicious computer advertisements
- Wake up after being repeatedly upset by MQ! Hate code out this MQ manual to help the journey of autumn recruitment
- asp.net大文件分块上传断点续传demo
- 每一个账号对应所有密码,再每一个密码对应所有账号暴力破解代码怎么写?...
- flashfxp 530 User cannot log in. ftp
猜你喜欢

每一个账号对应所有密码,再每一个密码对应所有账号暴力破解代码怎么写?...

Sort 5-count sort

laravel

Ansa secondary development - build ansa secondary development environment on Visual Studio code

FX3开发板 及 原理图

使用js直传oss阿里云存储文件,解决大文件上传服务器限制

一大早支付宝来短信说你中“奖”了?处理服务器挖矿病毒 - kthreaddi

关于web对接针式打印机问题,Lodop使用

5 亿用户,比微信还早四年……这个运营了 15 年的 APP 即将永久停服

排序5-计数排序
随机推荐
laravel
Leetcode daily practice - the number of digits in the offer 56 array of the sword finger
LwIP development | realize TCP server through socket
IT远程运维是什么意思?远程运维软件哪个好?
遭MQ连连干翻后的醒悟!含恨码出这份MQ手册助力秋招之旅
解决uniapp等富文本图片宽度溢出
Multiple commands produce ‘.../xxx.app/Assets.car‘问题
栈的介绍与实现(详解)
ANSA二次开发 - Visual Studio Code上搭建ANSA二次开发环境
“蔚来杯“2022牛客暑期多校训练营3 ACFHJ
Li Hongyi, machine learning 4. Deep learning
Configure HyperMesh secondary development environment on vs Code
重置grafana登录密码为默认密码
关于标准IO缓冲区的问题
Thoughts on solving the pop-up of malicious computer advertisements
The little red book of accelerating investment, "rush to medical treatment"?
ANSA二次开发 - 界面开发工具介绍
队列的介绍与实现(详解)
Fx3 development board and schematic diagram
5 亿用户,比微信还早四年……这个运营了 15 年的 APP 即将永久停服