图片的上传和读取

思路:图片保存在tomcat 虚拟目录下  数据库保存文件名

用IDEA设置omcat 虚拟目录的步骤如下(我将虚拟目录设置在F盘下img文件夹中):

图片的上传和读取

图片的上传和读取

右侧的Application context:  是你的访问路径  配置完成后 访问http://localhost:8080/pic/xxx.jpg

如果访问到图片 则配置成功

图片的上传和读取

  

图片的上传:

    所需的jar依赖

    

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>${commons-fileupload.version}</version>
</dependency>

    jsp表单:

     上传文件时form表单要设置entype属性  作用是让数据以二进制流传输 

     并且method必须设置位 post 方法

<form role="form" action="${pageContext.request.contextPath}/Shop/addWork.action" enctype="multipart/form-data" method="post">

<div class="form-group">
    <label>工作图片</label>
    <input type="file" name="pictureFile">
</div>

    controller

    接收文件 可以用 MultiparFile (能将文件名,扩展名等都接收过来)

    保存过程分四步

    1.首先要获取文件名称

    2.给文件设置新名称(防止名字重复)

    3.把图片保存到硬盘中(你的虚拟目录下)

    4.把新名称保存到数据库

    

@RequestMapping("/addWork")
public String addWork(Work work, MultipartFile pictureFile, HttpSession session) throws IOException {

    Integer id = (Integer) session.getAttribute("id");
    work.setShop_id(id);

    //获取源文件名称
    String pictureFile_name = pictureFile.getOriginalFilename();
    //用随机字符给文件新名称(防止重复)
    String newFileName = UUID.randomUUID().toString()+pictureFile_name.substring(pictureFile_name.lastIndexOf("."));
    //将图片保存到硬盘
    pictureFile.transferTo(new File("F:\\img\\"+newFileName));
    //将新图片名保存到数据库
    work.setPic(newFileName);

    ws.saveWork(work);
    return "forward:/Shop/showWork.action";
}

    图片的读取:

        在jsp 页面中 直接写路径名就可读取出来 src="/pic(你设置的tomcat访问路径)/文件名(数据库中读取的文件名)"

<img src="/pic/${works.pic}" width="100" height="100"/>
以上就是图片的上传以及读取。如有错误,欢迎指出!