当前位置:首页 » 文件管理 » jspservlet实现上传

jspservlet实现上传

发布时间: 2023-07-22 06:32:05

A. 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);

B. 用jsp、java实现上传图片,保存到数据库,从数据库中提取,显示到页面 这四步 我想问第一步,怎么上传图片

用jspSmartUpload组件来实现,用jsp+servlet在Servlet里实现的代码:

PrintWriter out = response.getWriter();
int count = 0;
// 实例化上传控件对象
SmartUpload su = new SmartUpload();
// 初始化操作
su.initialize(config, request, response);

// 设置上传文件最大字节数
su.setTotalMaxFileSize(100000);

//
try {
//禁止上传指定扩展名的文件
su.setDeniedFilesList("ext,bat,jsp");
} catch (SQLException e1) {
e1.printStackTrace();
}

try {
// 上传文件到服务器
su.upload();

File fileup = new File(request.getRealPath("upload"));
if(!fileup.exists()){
// 创建目录
fileup.mkdir();
}
// 处理多个文件的上传
for(int i = 0;i < su.getFiles().getCount();i++){
com.jspsmart.upload.File file = su.getFiles().getFile(i);
if(!file.isMissing()){ // 如果文件有效
// 保存文件到指定上传目录
file.saveAs("/upload/new."+file.getFileExt(), su.SAVE_VIRTUAL);
count = su.save("/upload");
}
}

} catch (SmartUploadException e) {

e.printStackTrace();
}
out.println(count +"file(s) uploaded");

如果你对这个上传组件不了解,最好是先去查查用法。。。

如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!

vaela

C. jsp+servlet 怎么实现文件上传

你要做文件上传吧 form表单里一定要设置这两个值enctype="multipart/form-data" method="post"
上传成功后会在tomcat里有那个文件 ,至于你说的要获取io流。那就需要找到那个文件给你写一下伪码吧:
//获得上传文件的路径

String path = getServletContext().getRealPath(webpath);

File file = new File(path);
file.getParentFile().mkdirs();
file.createNewFile();

// 获得流
InputStream in = item.getInputStream();
OutputStream out = new FileOutputStream(file);
不懂的再问我!
建议你用个上传组件,fileupload什么的

D. jsp+servlet实现文件上传与下载源码

上传:
需要导入两个包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
* 上传附件
* @author new
*
*/
public class UploadAnnexServlet extends HttpServlet {

private static String path = "";

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

/*
* post处理
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

path = this.getServletContext().getRealPath("/upload");

try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload up = new ServletFileUpload(factory);
List<FileItem> ls = up.parseRequest(request);

for (FileItem fileItem : ls) {
if (fileItem.isFormField()) {
String FieldName = fileItem.getFieldName();
//getName()返回的是文件名字 普通域没有文件 返回NULL
// String Name = fileItem.getName();
String Content = fileItem.getString("gbk");
request.setAttribute(FieldName, Content);
} else {

String nm = fileItem.getName().substring(
fileItem.getName().lastIndexOf("\\") + 1);
File mkr = new File(path, nm);
if (mkr.createNewFile()) {
fileItem.write(mkr);//非常方便的方法
}
request.setAttribute("result", "上传文件成功!");
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("result", "上传失败,请查找原因,重新再试!");
}
request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward(
request, response);
}

}

下载(i/o流)无需导包:
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 下载文件
* @author
*
*/
public class DownloadFilesServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 8594448765428224944L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

/*
* 处理请求
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String name = request.getParameter("fileName");

System.out.print("dddddddddd:" + name);
// web绝对路径
String path = request.getSession().getServletContext().getRealPath("/");
String savePath = path + "upload";

// 设置为下载application/x-download
response.setContentType("application/x-download");
// 即将下载的文件在服务器上的绝对路径
String filenamedownload = savePath + "/" + name;
// 下载文件时显示的文件保存名称
String filenamedisplay = name;
// 中文编码转换
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
try {
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(
filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
} catch (Exception e) {

}

}

}

热点内容
ftp的服务系统主要包括什么 发布:2025-02-03 21:41:33 浏览:304
换汽车压缩机 发布:2025-02-03 21:38:10 浏览:66
安卓版的迷你世界怎么登录 发布:2025-02-03 21:28:05 浏览:586
dt如何编译 发布:2025-02-03 21:16:59 浏览:564
unity调用脚本 发布:2025-02-03 21:13:21 浏览:268
php方法类 发布:2025-02-03 21:01:56 浏览:444
电脑基岩版材质包怎么安装到服务器里 发布:2025-02-03 20:57:33 浏览:391
linux文件组 发布:2025-02-03 20:53:51 浏览:330
db2存储执行变慢 发布:2025-02-03 20:42:21 浏览:766
滑板鞋脚本视频 发布:2025-02-02 09:48:54 浏览:433