当前位置:首页 » 文件传输 » jsp实现文件上传
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

jsp实现文件上传

发布时间: 2022-04-03 10:32:39

‘壹’ 如何用JSP实现文件的上传和下载,要对数据库进行什么操作

你的表单呢?他的意思等你上传完成后,你要把文件信息更新到数据库,当你在向用户展示时,只需要查询数据即可。可以再数据库建一个表,吧相应字段存起来,最重要的是存上你的图片路径和名字。

‘贰’ jspsmartupload组件实现文件上传上传到了哪里

1、上传有时候能成功,有时候不能成功: 如果使用eclipse运行应用,则应用默认部署在workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\这个目录里,ch1应该是你的工程的名字,SmartUpload的save方法是相对于工程根目...

‘叁’ jsp实现文件上传到mysql数据库并能下载文件模块案列

不知道你基础怎么样,这是最原始最简单的案例了,html代码是你要选择文件的界面,jsp代码请命名为smartupload_demo02.jsp(因为html里面表单的action是提交到这个页面,当然你可以改,html表单action与jsp名称一致就行)
另外还有很重要的一件事,你需要下载一个SmartUpload.jar插件放到你的web目录的lib文件夹下面,如果你不知道怎么下网络,再不行给个邮箱我发给你。不理解的地方可以联系我[email protected],希望可以帮到你。
html代码:
<html>
<head><title>www.mldnjava.cn,MLDN高端Java培训</title></head>
<body>
<form action="smartupload_demo02.jsp" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="uname"><br>
照片:<input type="file" name="pic"><br>
<input type="submit" value="上传">
<input type="reset" value="重置">
</form>
</body>
</html>
jsp代码:
<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="org.lxh.smart.*"%>
<%@ page import="cn.mldn.lxh.util.*"%>
<html>
<head><title>www.mldnjava.cn,MLDN高端Java培训</title></head>
<body>
<%
request.setCharacterEncoding("GBK") ;
%>
<%
SmartUpload smart = new SmartUpload() ;
smart.initialize(pageContext) ; // 初始化上传操作
smart.upload() ; // 上传准备
String name = smart.getRequest().getParameter("uname") ;
IPTimeStamp its = new IPTimeStamp(request.getRemoteAddr()) ; // 取得客户端的IP地址
String ext = smart.getFiles().getFile(0).getFileExt() ; // 扩展名称
String fileName = its.getIPTimeRand() + "." + ext ;
smart.getFiles().getFile(0).saveAs(this.getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName) ;
%>
<%=smart.getFiles().getFile(0).getFileName().matches("^\\w+.(jpg|gif)$")%>
<h2>姓名:<%=name%></h2>
<img src="../upload/<%=fileName%>">
</body>
</html>

‘肆’ JSP 前端大文件上传如何实现

jsp跟html一样的,上传文件三个要求
第一:post请求
第二:格式为file
第三:提交方式

‘伍’ jsp如何实现文件上传与下载

如果服务器端程序使用的是struts2框架的话,我会,其他的不会。
struts2:
对于上传,jsp页面只需要有个file类型的表单域,如<input type="file" name="xxx" />
struts2的接收请求的action中再写三个属性与这个表单域的名称对应起来,他们是,File类型的xxx,String类型的xxxFileName,String类型的xxxContentType,并其设置相应的set/get方法。则框架负责接收上传文件的字节流,解析文件名,文件类型,直接使用即可。
对于下载,只需要在action的配置文件中设置如下返回值类型和相应参数:
<result type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename=xxx </param> xxx为下载文件的文件名
</result>
且在action总写一个返回值类型为InputStream的getInputStream方法,此方法返回你要下载的文件的流即可。
ps:其中contentDisposition的配置信息中attachment代表点击下载时浏览器先弹出个保存位置的提示框,然后再决定是否下载,默认是inline,即直接打开文件。

‘陆’ jsp页面中如何视频文件上传的代码实现

jsp 获取视频文件进行播放 跟html没什么区别 可以调用不同播放器的代码 ,比如MEDIA播放器:
<OBJECT ID="mediaplayer" WIDTH="50%" HEIGHT="50%" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
<!--播放的文件的地址-->
<param name="url" value="http://www..com"/>
<!--去除右键菜单-->
<param name="enableContextMenu" value="false"/>
<param name="autoStart" value="true" />
</OBJECT>

‘柒’ 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什么的

‘捌’ 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 怎样实现文件上传

你下载一个jspsmart组件,网上很容易下到,用法如下,这是我程序的相关片断,供你参考: <%@ page import="com.jspsmart.upload.*" %>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
<%
String photoname="photoname";

// Variables
int count=0; // Initialization
mySmartUpload.initialize(pageContext); // Upload
mySmartUpload.upload();

for (int i=0;i<mySmartUpload.getFiles().getCount();i++){ // Retreive the current file
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i); // Save it only if this file exists
if (!myFile.isMissing()) {
java.util.Date thedate=new java.util.Date();
java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
photoname = df.format(thedate);
photoname +="."+ myFile.getFileExt();
myFile.saveAs("/docs/docimg/" + photoname);
count ++; } }
%>
<% String title="1";
String author="1";
String content="1";
String pdatetime="1";
String topic="1";
String imgintro="1";
String clkcount="1"; if(mySmartUpload.getRequest().getParameter("title")!=null){
title=(String)mySmartUpload.getRequest().getParameter("title");
title=new String(title.getBytes("gbk"),"ISO-8859-1");
}
if(mySmartUpload.getRequest().getParameter("author")!=null){
author=(String)mySmartUpload.getRequest().getParameter("author");
author=new String(author.getBytes("gbk"),"ISO-8859-1");
}
if(mySmartUpload.getRequest().getParameter("content")!=null){
content=(String)mySmartUpload.getRequest().getParameter("content");
content=new String(content.getBytes("gbk"),"ISO-8859-1");
}
if(mySmartUpload.getRequest().getParameter("pdatetime")!=null){
pdatetime=(String)mySmartUpload.getRequest().getParameter("pdatetime");
}
if(mySmartUpload.getRequest().getParameter("topic")!=null){
topic=(String)mySmartUpload.getRequest().getParameter("topic");
}
if(mySmartUpload.getRequest().getParameter("imgintro")!=null){
imgintro=(String)mySmartUpload.getRequest().getParameter("imgintro");
imgintro=new String(imgintro.getBytes("gbk"),"ISO-8859-1");
}
if(mySmartUpload.getRequest().getParameter("clkcount")!=null){
clkcount=(String)mySmartUpload.getRequest().getParameter("clkcount");
}
//out.println(code+name+birthday);
%>