JavaWeb图片上传随谈(一)

最近一段时间内经历了几次大的图片上传方法的变动,特意写下这几篇文章,以便学习和总结。
今天说的这个方法是一个很传统的图片上传方法,主要思路是页面表单提交图片文件,然后后台把这个图片文件写入本地,将本地图片路径作为一个字符串存入数据库。
鄙人采用的SSH2框架,为简化文章,框架本身的一些配置文件没有给出,可以通过方法路径的命名得知其含义

页面代码片段
 <form method="post" action="http://127.0.0.1/shanxia_serve/u/fileUpload_uploadImgForTest" enctype="multipart/form-data">
   <input type="file"  name="uploadFile" >

   <input type="submit"  value="OK" >

页面代码很简单,主要是表单里面有个文件属性定义,enctype=”multipart/form-data”,然后就是标签里面的name=”XX”,因为是表单提交,所以这里需要将其定义为name属性以便后台接受。

后台代码片段
private File uploadFile;//上传文件
 private String uploadFileFileName;//文件名
public File getUploadFile() {
        return uploadFile;
    }


    public void setUploadFile(File uploadFile) {
        this.uploadFile = uploadFile;
    }
    public String getUploadFileFileName() {
        return uploadFileFileName;
    }


    public void setUploadFileFileName(String uploadFileFileName) {
        this.uploadFileFileName = uploadFileFileName;
    }
public String uploadImg() throws IOException{


            String uuid = UUID.randomUUID().toString().replace("-", "");//重命名文件的文件体
            InputStream is=new FileInputStream(uploadFile);//将<input>标签里面的图片文件写入流文件InpuStream
            String uploadPath=ServletActionContext.getServletContext().getRealPath("/photos/");
            File toFile=new File(uploadPath,this.getUploadFileFileName());//目标文件,由文件位置和文件名(请求文件的文件名)组成
            /**
             * 这段代码用于重命名文件,以免文件被覆盖
             */
            int pot=toFile.getName().lastIndexOf(".");  
            String ext="";
              if(pot!=-1){  
                  ext=toFile.getName().substring(pot);  
              }else{  
                  ext="";  
              }  
              String newName=uuid+ext;  
              toFile=new File(toFile.getParent(),newName); //重命名文件完成
              /**
               * 将客户端的二进制数据流写入到服务器本地
               */
            OutputStream os=new FileOutputStream(toFile);
            byte[] buffer=new byte[1024];//缓冲空间大小 单位为KB
            int length=0;
            while((length=is.read(buffer))>0){
                os.write(buffer,0, length);
            }
            is.close();
            os.close();  //文件写入本地完成

            String webRoot=req.getSession().getServletContext().getRealPath("/");//获取文件在服务器项目文件夹的绝对路径
            String basePath="/photos/"+toFile.getName();//文件的相对路径
            String url=webRoot+basePath;//文件的完整路径,而接下来我们只需要将这个完整路径存入数据库即可
            PrintWriter out=resp.getWriter();
            out.print(urL);
            out.print("||success");

            return null;

    }

上述核心代码实现了接受页面传过来的图片文件,然后将其通过输入输出流文件的形式写入到服务器本地,然后获取文件本身的完整路径。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值