SpringMVC读取本地图片和上传图片

/**
     * 获取本地图片
     * @param pictureName //文件名
     * @return
     */
    @RequestMapping("/picReq")
    public void ShowImg(String pictureName, HttpServletRequest request, HttpServletResponse response) throws IOException{
        //文件名
        String imgFile = request.getParameter("imgFile");
        //这里是存放图片的文件夹地址
        String path= "F:/DreamCinemaImg";
        FileInputStream fileIs=null;
        OutputStream outStream = null;
        try {
            fileIs = new FileInputStream(path+"/"+pictureName);
            //得到文件大小
            int i=fileIs.available();
            //准备一个字节数组存放二进制图片
            byte data[]=new byte[i];
            //读字节数组的数据
            fileIs.read(data);
            //设置返回的文件类型
            response.setContentType("image/*");
            //得到向客户端输出二进制数据的对象
            outStream=response.getOutputStream();
            //输出数据
            outStream.write(data);
            outStream.flush();
        } catch (Exception e) {
            logger.info("系统找不到图像文件:"+path+"/"+imgFile);
            return;
        }finally {
            //关闭输出流
            outStream.close();
            //关闭输入流
            fileIs.close();
        }
    }

SpringMVC上传文件

1、首先先导入spring相关的依赖

2、导入文件上传的依赖

<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
</dependency>

3、springmvc配置文件添加上传文件的配置

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 限制文件上传的总大小(单位:字节),不配置此属性默认不限制 -->
        <property name="maxUploadSize" value="1048576000000"/>
        <!--指定文件写入内存的大小-->
        <property name="maxInMemorySize" value="1048576000"/>
        <!-- 设置文件上传的默认编码-->
        <property name="defaultEncoding" value="utf-8"/>
</bean>

4、代码

/**
     * 图片上传
     * @param file
     * @param picNum
     * @return
     */
    @RequestMapping("/uploadPic")
    @ResponseBody
    public ResponseView  addProduct(MultipartFile file, Integer picNum){
        ResponseView rv = new ResponseView();
        //构建文件目录
        File uploadDir = new File("F:/DreamCinemaImg");
        //如果目录不存在,则创建
        if(!uploadDir.exists()){
            uploadDir.mkdir();
        }
        //获取上传的文件名
        String fileName = file.getOriginalFilename();
        //构建一个完整的文件上传对象
        File uploadFile = new File(uploadDir.getAbsolutePath() + "/" + fileName);
        //判断文件是否存在
        if(!uploadFile.exists()) {
            try {
                //通过transferTo方法进行上传
                file.transferTo(uploadFile);
                rv.setCode(0);
                //把文件名放入响应视图
                rv.setData(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                rv.setCode(500);
                throw new RuntimeException(e.getMessage());
            }
        }else{
            rv.setCode(400);
        }
        return rv;
    }

猜你喜欢

转载自www.cnblogs.com/nisiweiLIQIYONG/p/10053471.html
今日推荐