上传MultipartFile文件获取inputstream报错

第一次读取文件后,再次读取就没有了

  /****
     * 截取全景图截图并保存到服务器,返回截图名
     * @param source
     * @param targetFile
     * @param startAcross
     * @param StartEndlong
     * @param width
     * @param hight
     * @return
     * @throws Exception
     */
    public  String cutImage(InputStream source, String targetFile, int startAcross, int StartEndlong, int width,
                          int hight) throws Exception {
        // 取得图片读入器
        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader reader = readers.next();
        // 取得图片读入流
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader.setInput(iis, true);
        // 图片参数对象
        ImageReadParam param = reader.getDefaultReadParam();
        Rectangle rect = new Rectangle(startAcross, StartEndlong, width, hight);
        param.setSourceRegion(rect);
        BufferedImage bi = reader.read(0, param);
        String uuid = "";
        uuid = UUID.randomUUID().toString().replaceAll("-", "") + System.currentTimeMillis() + Tools.getRandomStr();
        String path=uuid+".jpg";
        String newPath=targetFile+path;
        File file=new File(newPath);
        ImageIO.write(bi, newPath.split("\\.")[1],file);
        return  path;
    }

 

使用MultipartFile对象生成多个相同的文件

mvc的MultipartFile对象不能在一个方法里被重复使用,所以如果对一个上传的文件需要创建相同的多个文件,就需要把文件对象转成输入流进行操作,就不会报错,代码如下

String trueFileName=fileName;

                     // 获得输入流:  
                     InputStream picture=null;
                     try {
                      picture = file.getInputStream();
              } catch (IOException e3) {
              e3.printStackTrace();
              }    
                     // 设置存放图片文件的路径
                     path=servletPath+"\\"+advertise.getUsername()+"\\"+Adorderid+"\\"+city1+"\\"+area1+"\\"+dateStr+"\\";
                     System.out.println("path"+path);
                     dest=new File(path);
                     //检测是否存在目录
  
  if(!dest.exists()){
  dest.mkdirs();
  }
                     // 转存文件到指定的路径
          try {       
             
              String destPath =path + trueFileName;
              System.out.println("destPath=" + destPath);
              //真正写到磁盘上
              File file2 = new File(destPath);
              OutputStream out = new FileOutputStream(file2);          
              int length = 0;
              byte[] buf = new byte[1024];
              // in.read(buf) 每次读到的数据存放在buf 数组中
              while ((length = picture.read(buf)) != -1) {
                  //在buf数组中取出数据写到(输出流)磁盘上
                  out.write(buf, 0, length);
              }
              picture.close();
              out.close();
          } catch (Exception e) {
          System.out.println(e.toString());
          }

 

posted on 2018-07-17 16:57  让代码飞  阅读(3004)  评论(0)    收藏  举报

导航

一款免费在线思维导图工具推荐:https://www.processon.com/i/593e9a29e4b0898669edaf7f?full_name=python