web项目中图片上传

最近一直在做一个项目,但是有好多的东西都是第一次碰到,上网上查了很多资料,但是由于基础薄弱,只是堪堪了解一点。
我所想实现的是,在后台页面上传图片,存放路径到数据库中,而前台页面通过数据库可以查到,然后在页面显示,而上传的图片要保存到我在项目中所建的文件夹内,服务器上有临时存放的位置String root = ServletActionContext.getServletContext().getRealPath("/upload");但是服务器清除的时候会把这些上传的文件就给清除了。
我现在做到的是,通过拷贝临时文件夹内的文件,保存到我所建的文件夹内,在这里记下以防止我遗忘。所用ssi框架,struts2,spring,mybatis,数据库orca,服务器tomcat。
1,前台页面
<form action="uploads" method="post" enctype="multipart/form-data">
        <input type="file" name="file"> 
        <input type="submit">
    </form>
发送

action请求到配置文件struts.xml里寻找

<action name="uploads" class="net.test.Controllers" method="upload">
            <result name="testUpload" ype="redirect">/file.jsp</result>
        </action>
public String upload() throws IOException {
        // 得到文件存放的临时路径
        String root = ServletActionContext.getServletContext().getRealPath(
                "/upload");
        System.out.println("那这个呢" + root);
        InputStream is = new FileInputStream(file);

        // 原file文件
        File dest = new File(root, fileFileName);// 服务器的文件

        OutputStream os = new FileOutputStream(dest);
        // FileOutputStream fot=new FileOutputStream("D://");
        // while(is.read()>-1){
        // fot.write(b);
        // }

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

        // 因为file是存放在临时文件夹的文件,我们可以将其文件名和文件路径打印出来,看和之前的fileFileName是否相同
        System.out.println("file: " + file.getName());
        System.out.println("file: " + file.getPath());

        byte[] buffer = new byte[500];
        int length = 0;

        while (-1 != (length = is.read(buffer, 0, buffer.length))) {
            os.write(buffer);
        }
        os.close();
        is.close();

        // 通过JVM读取java.io.tmpdir属性取得临时文件夹
        // File targetDir = new File(System.getProperty("java.io.tmpdir"));

        String root1 = this.getClass().getClassLoader().getResource("")
                .getPath();
        System.out.println("打印这个" + root1);

        // 获得文件路径
        String fileuil = "D://yzg_new//youtuWeb//WebContent//upload";
        haha = fileuil + fileFileName;

        // 拷贝文件(a,b)a到b
         FileUtils.copyFileToDirectory(dest, new File(fileuil));// 完成了文件的拷贝工作

        // String file_real_path= ServletContext.getRealPath("mypath/filename");
        return "testUpload";

    }

在项目中新建upload文件夹,上传成功后刷新一下文件就会发现文件出现在目录里。
然后问题出现了,我放进数据库里因该是什么路径呢?那前台显示的呢?有经验的朋友看到的话,不妨给我讲一下,麻烦了。如果不懂得朋友有什么新收获,一块来研究一下吧。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值