使用springMVC实现上传下载图片

上传多张图片代码:

public static final String PICTUREURL = "/mnt/pic/";//图片路径
public static final String PC_PICTUREURL = "E:\\pic";//图片路径

@RequestMapping("/uploadPics.do")
    public RetObj uploadPics(@Param("file") MultipartFile[] files,@Param("trendId") Integer trendId){
        RetObj ret = new RetObj();
        try {
            if (files!=null &&files.length>0){
                List<Picture> result = new LinkedList<>();
                int i =1;
                for (MultipartFile file : files){
                    String filename = "picture_" + UUID.randomUUID() + ".jpg";//生成唯一图片路径
                    if (!file.isEmpty()) {
                        try {
                            File filepath = new File(PC_PICTUREURL);
                            if (!filepath.exists())
                                filepath.mkdirs();
                            // 文件保存路径
                            String savePath = PC_PICTUREURL + filename;
                            // 转存文件
                            file.transferTo(new File(savePath));
                            //图片路径存到数据库
                            Picture picture = new Picture();
                            picture.setTrendid(trendId);
                            picture.setPath(savePath);
                            picture.setSort(i);
                            pictureService.insert(picture);
                            i++;
                            result.add(picture);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                ret.setObj(result);
            }else {
                ret.Fail("请选择上传的图片");
                return ret;
            }
        }catch (Exception e){
            log.error("图片上传失败"+ ExceptionUtil.getStackStr(e));
            ret.Fail("网络异常");
        }
        return ret;
    }

查看图片代码:

@RequestMapping("/getPic.do")
    public void getPic(HttpServletResponse response, @Param("url") String url){
        File file = new File(url);
        FileInputStream fis =null;
        try {
            if (!file.exists()){
                return;
            }
            fis = new FileInputStream(file);
            final byte[] buf = new byte[1024];
            while (fis.read(buf)>0){
                response.getOutputStream().write(buf);
            }
        }catch (Exception e){
            log.error("图片上传失败"+ ExceptionUtil.getStackStr(e));
        }finally {
            if (fis!=null){
                try {
                    fis.close();
                }catch (Exception e){

                }
            }
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        }

    }

你可能感兴趣的:(springboot学习)