首页 > 编程知识 正文

jsp上传文件部分代码(jsp 文件上传)

时间:2023-12-16 10:45:32 阅读:316295 作者:RJSG

本文目录一览:

jsp上传文件代码!

其实就是读流的形式。我这有个struts1的,自己研究下。可以批量上传配置文件:#路径请用双

path=c:\test\

#大小为b

fileSize=5000

#文件类型用","隔开

fileType=jpg,txt主要类:// 路径常量

public static final String FILEPATH = "path";

// 文件大小

public static final String FILESIZE = "fileSize";

// 文件类型

public static final String FILETYPE = "fileType"; /**

* @param key:资源文件key值

* @return 返回对应key的value

*/

public static String getValueByKey(String key) {

String rKey = "";

CommonUtil util = new CommonUtil();

// 获取资源文件流

InputStream in = util.getClass().getResourceAsStream(

"/upload.properties"); Properties props = new Properties();

try {

// 加载资源文件

props.load(in);

// 获取资源文件对应key值

rKey = props.get(key).toString();

in.close();

} catch (IOException e) {

e.printStackTrace(); }

return rKey; // 遍历所有key值

// Set set = props.keySet();

// Iterator it = set.iterator();

// System.out.println("Begin ...");

// while(it.hasNext()){

// System.out.println((String)it.next());

// }

// System.out.println("End");

} /**

* 根据系统时间+两位数字随机数产生文件名

*

* @return 例:2010091521202315

*/

public static String getFileName() {

// 格式化日期

SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");

String fileName = s.format(new Date());

// 随机数

Random r = new Random();

int random = 0;

do {

random = r.nextInt(100);

} while (random 10);

// 连接字符串

fileName += random;

return fileName;

} /**

* 上传文件集合

*

* @param files:FormFile的集合

* @param code:数据字典模块路径id

* @param fileName:文件真实名称

* @return 上传后的文件id数组

*/

public static String[] filesUpload(List files, int code, String[] fileName)

throws IOException, Exception {

// 输出文件名

for (int i = 0; i fileName.length; i++) {

System.out.println("文件" + (i + 1) + "名字:" + fileName[i]);

}

// 获取资源文件上传路径

String path = CommonUtil.getValueByKey(CommonUtil.FILEPATH);

System.out.println("资源文件路径:" + path);

// 获取大小文件上限

long fileSize = Long.parseLong(CommonUtil

.getValueByKey(CommonUtil.FILESIZE));

System.out.println("文件上限大小:" + fileSize + "b");

// 获取文件类型

String types = CommonUtil.getValueByKey(CommonUtil.FILETYPE).toString();

System.out.println("限制文件类型:" + types);

// 数组转为集合

List fileTypes = Arrays.asList(types.split(",")); // 首先遍历文件集合判断是否合法

for (Iterator iterator = files.iterator(); iterator.hasNext();) {

// 单个文件

FormFile file = (FormFile) iterator.next();

// 文件类型

String ext = file.getFileName().substring(

file.getFileName().lastIndexOf(".") + 1,

file.getFileName().length());

// 遍历文件类型集合进行判断

if (!fileTypes.contains(ext)) {

throw new Exception("不允许上传" + ext + "类型文件");

}

if (fileSize file.getFileSize()) {

throw new Exception("上传的文件过大");

}

}

for (Iterator iterator = files.iterator(); iterator.hasNext();) {

// 单个文件

FormFile file = (FormFile) iterator.next(); /*

* 。。。。。。。。。。。。。。。实际上传路径

*/

// 根据实际上传路径新建文件夹

new File(path).mkdirs();

// 文件输出路径

String savePath = path + getFileName() + ".jpg";

System.out.println("文件输出路径" + savePath);

if (file.getFileSize() 10) {

// 输入流

InputStream input = file.getInputStream();

byte[] b = new byte[1024];

// 输出流

FileOutputStream fileoutput = new FileOutputStream(savePath);

// 开始输出

while (input.read(b) != -1) {

fileoutput.write(b);

}

fileoutput.close();

input.close();

// 文件上传结束

}

}

/*

* 。。。。。。。。。。。。。。获取上传后的文件名

*/

return null;

}

Jsp上传图片到指定文件夹下 求详细代码

String time = new SimpleDateFormat("yyyyMMddHHmmss")

.format(Calendar.getInstance().getTime());// 得到系统时间

// 上传技术

SmartUpload up = new SmartUpload();

// 进行初始化

up.initialize(this.getServletConfig(), request, response);

// 开始上传

try {

up.upload("utf-8");//设置编码方式。

int id = Integer.parseInt(up.getRequest().getParameter("id"));// 商品编号

SmartFiles sf = up.getFiles();// 得到上传的所有图片

SmartFile file = sf.getFile(0);// 根据索引得到上传图片 多个图片可以用循环:

String type = file.getFileExt();// 得到图片后缀名

String folder = "tp/";// 指定文件夹

String path = folder + time + "." + type;// 路径

System.out.println(path + "路径");

file.saveAs(request.getRealPath("/") + path);// 保存图片

} catch (Exception e) {

e.printStackTrace();

}

//你搞个邮箱我把SmartUploadjar包 发给你吧。 //设置from提交

/*form action="SellerServet" method="post"

enctype="multipart/form-data"*/ // 加上 enctype="multipart/form-data

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上传文件的代码

%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%

%@ page language="java" import="java.io.*,com.jspsmart.upload.*"%

HTMLHEAD

meta http-equiv="Content-Type" content="text/html";charset=UFT-8

TITLESave upload  /TITLE

/HEAD  

BODY  

%

 // 将上传文件全部保存到指定目录创建文件夹使用绝对路径

String uploadPath =request.getRealPath("/")+"/images/";

java.io.File fdir = new java.io.File(uploadPath);

if(!fdir.exists()){

    fdir.mkdirs();

}

  

SmartUpload su = new SmartUpload();

su.initialize(pageContext);

// 设定上传限制

// 1.限制每个上传文件的最大长度。

//su.setMaxFileSize(5120000); //5M

// 2.限制总上传数据的长度。

//su.setTotalMaxFileSize(25600000);//5M*5

// 3.设定允许上传的文件(通过扩展名限制)。

//su.setAllowedFilesList("gif,jpg,png,bmp,GIF,JPG,PNG,BMP");

// 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,

//jsp,htm,html扩展名的文件和没有扩展名的文件。

//su.setDeniedFilesList("exe,bat,jsp,htm,html,,");

// 上传文件

su.upload();

String x = su.getRequest().getParameter("x") ;

 

out.println("table border='1' width='560'");

out.println("tr");

out.println("th文件名/th");

out.println("th文件大小/th");

out.println("/tr");

for(int i=0;isu.getFiles().getCount();i++){

    com.jspsmart.upload.File file=su.getFiles().getFile(i);

    if(file.isMissing()){

        continue;

    }

    out.println("tr");

    out.println("td"+file.getFileName()+"/td");

    out.println("td"+file.getSize()+"/td");

    out.println("/tr");

    String ext="."+file.getFileExt();

    String strtemp=uploadPath+"/"+x+ext;

    

    file.saveAs(strtemp);

}

out.println("/table");

%

/body

/html

上面是完整的代码。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。