當前位置:首頁 » 文件傳輸 » 上傳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+"個文件");
%>