SmartUpload上传文件

上传文件的两种:

·第一种:上传到数据库中保存;

|-如果上传的内容大的话,这种方式不方便;

·第二种:上传到Web根目录种的某个文件夹中保存;

|-可以上传较大的内容;

下面例子是使用第二种方法:smartUpload

Smarupload01.html

<html>

<head>

<title>smartupload</title>

</head>

<body>

<form action="smartupload01.jsp" method="post" enctype="multipart/form-data">//封装MIME类型

用户姓名:<input type="text" name="uname"><br>

上传的图片:<input type="file" name="pic"><br>

<input type="submit" value="上传">

</form>

</body>

</html>

smartupload01.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>

<jsp:useBean id="smartupload" class="org.lxh.smart.SmartUpload"/>

<html>

<head>

<title>smartupload</title>

</head>

<body>

<%

request.setCharacterEncoding("GBK") ;

smartupload.initialize(pageContext) ; // 初始化上传

smartupload.upload() ; // 准备上传

String name = smartupload.getRequest().getParameter("uname") ;//因为封装了MIME类型后,不能直接利用request来接受参数了,必须通过smartupload提供 getRequest来代替request

smartupload.save("upload") ; // 保存WEB根目录下的upload文件

%>

<h1><%=name%></h1>

</body>

</html>

改善上面的代码, 使得可以保存时候给文件定义一个名字;

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>

<jsp:useBean id="smartupload" class="org.lxh.smart.SmartUpload"/>

<html>

<head>

<title>smartupload</title>

</head>

<body>

<%

request.setCharacterEncoding("GBK") ;

smartupload.initialize(pageContext) ; // 初始化上传

smartupload.upload() ; // 准备上传

String name = smartupload.getRequest().getParameter("uname") ;

name = name + "." + smartupload.getFiles().getFile(0).getFileExt() ;

String fileName = this.getServletContext().getRealPath("/") + "upload/" + name ;

smartupload.getFiles().getFile(0).saveAs(fileName) ;//给文件定义一个名字,使得上传上去的文件不会出现同名而覆盖

%>

</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值