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

上传jsp大马

发布时间: 2022-04-26 09:25:41

㈠ 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 大马 怎么反弹bash

jsp所需要的服务器环境非常简单,只需要下载tomcat,根据网络上图文安装教程,安装完之后,将jsp的工程放在work文件夹,就可以启动你的项目运行了。

㈢ jsp如何上传文件

只是jsp部分的话,只要在form标签里加一个“enctype="multipart/form-data"”就好了,读取下载的话只要弄个commons-fileupload之类的插件就很容易解决
这里是下载部分的核心代码:
<%@ page contentType="text/html;charset=gb2312" import="com.jspsmart.upload.*" %>
<%
String sUrl = (String)request.getAttribute("fileurl");
SmartUpload su = new SmartUpload();
su.initialize(pageContext);
//设定contentDisposition为null以禁止浏览器自动打开文件,保证点击链接后是下载文件。若不设定,则下载的文件扩展名为doc时,浏览器将自动用word打开它;扩展名为pdf时,浏览器将用acrobat打开。
su.setContentDisposition(null);
su.downloadFile(sUrl);
%>
但是归根结底,你还是要一个存放文件路径的数据库啊,否则你下载时候下载地址每次都写死或者手动输入??如果要动态读取的话还是要建一个存放文件路径的数据库的

㈣ jsp简单上传代码

servlet文件上传
login.jsp

<%@ page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
输入用户名<input typ="text" name ="username">
<input type="file"name="file"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

result.jsp

<%@ page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>上传结果页面</title>
</head>
<body>
username:${requestScope.username }
filename:${requestScope.file }
</body>
</html>

UploadServlet.java

package com.test.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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;

public class UploadServlet extends HttpServlet {

public UploadServlet() {

}

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

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getSession().getServletContext().getRealPath("/upload");
DiskFileItemFactory factory = new DiskFileItemFactory();

factory.setRepository(new File(path));
factory.setSizeThreshold(1024 * 1024);

ServletFileUpload upload = new ServletFileUpload(factory);

try
{
List<FileItem>list = upload.parseRequest(request);
for(FileItem item:list){
if(item.isFormField()){
String name = item.getFieldName();
String value = item.getString("utf-8");
request.setAttribute(name, value);
}
else{
String name = item.getFieldName();
String value = item.getName();
int start = value.lastIndexOf("\\");
String fileName = value.substring(start+1);
request.setAttribute(name, fileName);
System.out.println(fileName);
OutputStream os = new FileOutputStream(new File(path,fileName));
InputStream is = item.getInputStream();

byte[] buffer = new byte[400];
int length = 0;
while((length = is.read(buffer))>0){
os.write(buffer,0,length);
}
os.close();
is.close();
}
}
}
catch(Exception e){
e.printStackTrace();
}

request.getRequestDispatcher("/result.jsp").forward(request, response);
}

}

Struts文件上传

1.创建一个工程:

创建一个JSP页面内容如下:

<body>

<form action="uploadAction.do" method="post" enctype="multipart/form-data" >

<input type="file" name="file">

<input type="submit">

</form>

</body>

2.创建一个FormBean继承ActionForm

其中有个private FormFile file ;属性。FormFile类的全名为:org.apache.struts.upload.FormFile

3.创建一个UploadAction继承自Action

然后重写Action的execute()方法:

代码如下:

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) {

UploadForm uploadForm = (UploadForm) form;

if(uploadForm.getFile()!=null)

FileUtil.uploadFile(uploadForm.getFile(), "e:/abc/accp");

return null;

}

4.创建FileUtil工具类,里面实现上传的文件的方法:

关键代码如下:

public class FileUtil

{

/*** 创建空白文件

* @param fileName 文件名

* @param dir 保存文件的目录

* @return

*/

private static File createNewFile(String fileName,String dir)

{

File dirs = new File(dir);

//看文件夹是否存在,如果不存在新建目录

if(!dirs.exists())

dirs.mkdirs();

//拼凑文件完成路径

File file = new File(dir+File.separator+fileName);

try {

//判断是否有同名名字,如果有同名文件加随机数改变文件名

while(file.exists()){

int ran = getRandomNumber();

String prefix = getFileNamePrefix( fileName);

String suffix = getFileNameSuffix( fileName);

String name = prefix+ran+"."+suffix;

file = new File(dir+File.separator+name);

}

file.createNewFile();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return file;

}

/**

* 获得随机数

* @return

*/

private static int getRandomNumber() {

Random random = new Random(new Date().getTime());

return Math.abs(random.nextInt());

}

/**

* 分割文件名 如a.txt 返回 a

* @param fileName

* @return

*/

private static String getFileNamePrefix(String fileName){

int dot = fileName.lastIndexOf(".");

return fileName.substring(0,dot);

}

/**

* 获得文件后缀

* @param fileName

* @return

*/

private static String getFileNameSuffix(String fileName) {

int dot = fileName.lastIndexOf(".");

return fileName.substring(dot+1);

}

/**

* 上传文件

* @param file

* @param dir

* @return

*/

public static String uploadFile(FormFile file,String dir)

{

//获得文件名

String fileName = file.getFileName();

InputStream in = null;

OutputStream out = null;

try

{

in = new BufferedInputStream(file.getInputStream());//构造输入流

File f = createNewFile(fileName,dir);

out = new BufferedOutputStream(new FileOutputStream(f));//构造文件输出流

byte[] buffered = new byte[8192];//读入缓存

int size =0;//一次读到的真实大小

while((size=in.read(buffered,0,8192))!=-1)

{

out.write(buffered,0,size);

}

out.flush();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

finally

{

try {

if(in != null) in.close();

} catch (IOException e) {

e.printStackTrace();

}

try {

if(out != null) out.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return null;

}

}

㈤ struts2存在命令执行漏洞,上传webshell文件等什么意思

就是控制网站 传一个脚本木马上去 (可以是一句话,用中国菜刀控制你的网站 或者直接传jsp大马控制)。最起码有相当于你网站的ftp权限。Windows的服务器一般jsp的脚本权限都是系统权限,linux也权限很高。

㈥ JSP 前端大文件上传如何实现

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

㈦ 用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);
%>

㈧ jsp文件上传如何规定大小

这是jspsmartupload本身一个缺陷!用jspsmartupload上传东西,当大小超过了某个值后就无法上传了.也就报出了以下异常:
java.lang.OutOfMemoryError: Java heap space

如果是上传小的东西,用这个jspsmartupload这个组件足够了,但是上传大的文件就不行了.建议用commonupload组件.
究其原因在jspsmartupload源码中有:
m_totalBytes = m_request.getContentLength();
m_binArray = new byte[m_totalBytes];
int j;
for(; i < m_totalBytes; i += j)
....

而m_request就是HttpServletRequest,它一次将文件流全部读入内存中,也就造成m_totalBytes超级的大,而在new byte[m_totalBytes];时就在内存在分配了一个超大的空间,内存受不了也就直接报异常了.所以除非改掉这种方式的上传否则是没法解决这个问题的.

而commonupload就不一般了,它可以设置一次读取文件最大部分是多少,比部文件有200Mb,你设置一次读取文件的大小是4MB,那么也就超过了一次读4MB到内存,然后就此4MB的部分写入硬盘中的临时文件中,然后再读取下面的4MB,接着把内存的东西刷到硬盘中.也就不会一次读入内存的东西太多,而造成内存的泻漏.

以下是使用commonupload上传的部分代码
String fileName = " ";
String appPath = request.getSession().getServletContext().getRealPath("/") ;
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(cacheSize); //缓冲大小
File temFile = new File(appPath+tempFileFold); //超过缓冲小放在临时文件夹,再一步一步上传
if(!temFile.exists()){
temFile.mkdirs();
}
factory.setRepository(temFile);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize); //最大大小

List fileList = null ;

try {
fileList = upload.parseRequest(request);

} catch (FileUploadException e) {
if (e instanceof SizeLimitExceededException) {
System.out.println("超过大小了,返回!");
double maxSize = maxFileSize/(1024.0*1024.0);
if(maxSize>1.0){
float fileSize = Math.round(maxSize*1000)/1000;
request.setAttribute("message", MessageResource.readByString("file_size_overflow")+fileSize+"M");
}else{
double kMaxSize = maxFileSize/(1024.0);
float fileSize = Math.round(kMaxSize*100)/100;
request.setAttribute("message", MessageResource.readByString("file_size_overflow")+fileSize+"K");
}
request.setAttribute("page", request.getParameter("failpage"));
System.out.println("page:"+request.getAttribute("page")+" messgae:"+request.getAttribute("message"));
return "";
}
e.printStackTrace();
}

if (fileList == null || fileList.size() == 0) {
System.out.println("空文件,返回!");
return "";
}

// 得到所有上传的文件
Iterator fileItr = fileList.iterator();
// 循环处理所有文件
while (fileItr.hasNext()) {
FileItem fileItem = null;
String path = null;
long size = 0;
// 得到当前文件
fileItem = (FileItem) fileItr.next();
// 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
if (fileItem == null || fileItem.isFormField()) {
continue;
}
// 得到文件的完整路径
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
if ("".equals(path) || size == 0) {

System.out.println("空文件2,返回!");
return "" ;
}

// 得到去除路径的文件名
String t_name = path.substring(path.lastIndexOf("\\") + 1);
// 得到文件的扩展名(无扩展名时将得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
String[] allowFiles = allowedFilesList.split(",");
boolean isPermited = false ;
for(String allowFile:allowFiles){
if(t_ext.equals(allowFile)){
isPermited = true ;
break ;
}

}
if(!isPermited){
request.setAttribute("message", t_ext+MessageResource.readByString("file_format_error")+allowedFilesList);
request.setAttribute("page", request.getParameter("failpage"));
System.out.println(t_ext+"文件格式不合法,合法文件格式为:"+allowedFilesList);
return "" ;
}

long now = System.currentTimeMillis();
// 根据系统时间生成上传后保存的文件名
String newFileName = String.valueOf(now)+"."+t_ext;
// 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下
File desctemFile = new File(appPath + fileLocationFold); //超过缓冲小放在临时文件夹,再一步一步上传
if(!desctemFile.exists()){
desctemFile.mkdirs();
}
String u_name = appPath + fileLocationFold
+ newFileName ;
fileName = fileLocationFold+newFileName ;

try {

fileItem.write(new File(u_name));

} catch (Exception e) {

e.printStackTrace();
}

}

return fileName ;

㈨ 请问jsp页面如何能获取到上传文件的大小,我想通过获取的大小,判断该文件是否可以被上传,请详细点,谢谢

因权限和安全限制,js是不能获得本地文件大小的,除非安装控件。
jsp获取上传文件大小方法如下:
long size=request.getContentLength() ;
在文件准备上传之前就可以得到其大小。
当然了,在客户端基本上不大可能获取大文件大小的,必须是文件提交上传开始后,在服务端获取得到的,request.getContentLength() ; 可以在接受数据流之前就可以获得当前要上传的文件流大小。 这样你可以在服务端控制文件上传之前是否允许继续接受数据流。

㈩ 跪求jsp文件上传代码。

我这里写了个例子,希望对你有帮助
Upload.jsp 里面写

<form action="checkFile.jsp" enctype="multipart/form-data" method="post" name="checkFile">
<table>
<tr>
<td><input type="file" name="file1"/></td>
</tr>
<tr>
<td><input type="file" name="file2"/></td>
</tr>
<tr>
<td><input type="file" name="file3"/></td>
</tr>
<tr>
<td><input type="file" name="file4"/></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="上传" /></td>
</tr>
</table>
</form>

checkFile.jsp 里面代码

<%@ page language="java" import="java.util.*, com.jspsmart.upload.*"
pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%
SmartUpload su = new SmartUpload();
//初始化smartupload对象
su.initialize(pageContext);
try {
su.setDeniedFilesList("exe,bat,vbs,php,jsp,html,asp,aspx");
su.setAllowedFilesList("jpg,gif,rar,zip,doc,docx,xml,txt");
su.setCharset("utf-8");
su.upload();
} catch (Exception e) {
e.printStackTrace();
%>
<script type="text/javascript">
alert("你选择的文件不允许上传,或者文件过大,请返回检查");
</script>
<%
}
int count = su.getFiles().getCount();//文件个数
String pathcs=null;
for (int i = 0; i < count; i++) {
File file=su.getFiles().getFile(i);
file.setCharset("utf-8");
Random rd= new Random();
int rds=rd.nextInt(1000);
String filepath="upload\\"+rds+file.getFileName();
file.saveAs(filepath,SmartUpload.SAVE_VIRTUAL);
pathcs=filepath;
out.print("路径为:"+pathcs+"</br>");
out.print("上传成功"+"</br>");
}
out.print("你一共上传了"+count+"个文件");
%>