您现在的位置:计算机技术学习网 > 技术中心 > WEB编程 > JSP >

JSP上传文件(如图片)的最简单的Demo

来源:未知 责任编辑:责任编辑 发表时间:2014-01-25 11:34 点击:

<%@ page contentType="text/html; charset=gb2312"%>
<%@ page import="com.jspsmart.upload.*"%>


<%@ page import="java.util.Calendar,java.io.File"%>
<%
request.setCharacterEncoding("gb2312");

try{
SmartUpload su = new SmartUpload();          /// 上传文件组件
long file_max_size = 4000000;
   su.initialize(pageContext);// 上传初始化
   su.upload();
   // 将上传文件全部保存到指定目录
   String temp="upload/images";
   //创建文件夹使用绝对路径
String uploadPath =request.getRealPath("/")+temp;
//如果文件夹不存在,则创建此文件夹
if(!new File(uploadPath).isDirectory()){
new File(uploadPath).mkdirs();
}
Files files=su.getFiles();
//得到上传的文件
com.jspsmart.upload.File file = su.getFiles().getFile(0);

if(file.isMissing()){
System.out.println("missing");
}
String postfix="."+file.getFileExt();
//为上传的文件起别名
System.out.println("后缀名是:" + postfix);
if(!postfix.equals(".jpg")){
%>
<script type="text/javascript">
alert("不支持此图片格式");
</script>
<%
}else{
String fileName = "test";
//这个就是可以得到图片的路径了
String strtemp=uploadPath+"/"+ fileName + postfix;
System.out.println(strtemp);
file.saveAs(strtemp);  ///参数是路径 (完整)

%>
<script>
alert("图片上传成功!");
</script>
<%
}
}catch (Exception e){
 System.out.println(e.getMessage());
%>
<script type="text/javascript">
alert("图片上传失败!");
</script>
<%
}
%>


</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>首页</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="dscription" content="This is my page">
  </head>
  <body>
  <form action="ImageUpload.jsp"  method="post" enctype="multipart/form-data">
  <table>www.2cto.com
        <tr>
        <td width="120" align="center">路径:</td>

发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • JSP与Servlet
  • 自己动手写MiniBBS系列(基本篇)之用户登录
  • JSP取当前日期
  • JDBC 入门(一)
  • 打开一个jsp页面默认查询所有数据,调用action
  • 使用JSP标签库验证用户的输入(2)完
  • WIN98/2000下的jsp服务器
  • 自定义JSP标签(tag)浅议
  • Struts学习傻瓜式入门篇
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1