文件上传的小代码片段

1:在jsp页面的代码如下:

<%

//定义上载文件的最大字节
int MAX_SIZE = 102400 * 102400;
// 创建根路径的保存变量
String rootPath;
//声明文件读入类
DataInputStream in = null;
FileOutputStream fileOut = null;


String photo = null;
//取得客户端的网络地址
String remoteAddr = request.getRemoteAddr();
//获得服务器的名字
String serverName = request.getServerName();
String serverAddress=request.getServletPath();


System.out.println("remoteAddr:" + remoteAddr + " serverName:"
+ serverName+"serverAddress:"+serverAddress);


//取得互联网程序的绝对地址
String realPath = request.getRealPath("");


System.out.println("realPath:" + realPath);


realPath = realPath.substring(0, realPath.lastIndexOf("\\"));


//创建文件的保存目录
rootPath = "/Zhuxn/photos/";


SmartUpload upload = new SmartUpload();
upload.initialize(pageContext);
upload.setMaxFileSize(MAX_SIZE);
upload.setTotalMaxFileSize(MAX_SIZE);
upload.setAllowedFilesList("jpg,jpeg,bmp,png");


try {
upload.upload();
photo = rootPath + upload.getFiles().getFile(0).getFileName();


System.out.println("rootPath:" + rootPath);
File fileDir = new File(rootPath);
if (!fileDir.exists()) {
fileDir.mkdirs();
}


int count = upload.save(rootPath);
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();

%>

说明:由于知识展示代码片段,可能会出现不能完整运行的问题。


2:上面的代码依靠了一个第三方的扩展包jspSmartUpload.jar,可以在网上下载。


3:在文件上传的前台界面的表单的form属性上,注意要添加enctype="multipart/form-data",例如:



以上则可以完成文件的上传,在这里展示的是上传图片。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值