码迷,mamicode.com
首页 > 编程语言 > 详细

javaWeb文件上传和下载

时间:2020-03-08 17:33:45      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:autowired   code   dao   tty   last   tps   header   web   interface   

第一步

  1. 先新建一个com.aaa.util包
  2. 在包里新建一个FileUtil工具类(包括上传和下载方法)
public class FileUtil {
    /**
     * 通用上传方法
     * @param savePath
     * @param multipartFile
     * @return
     */
    public static String uploadFile(String savePath, MultipartFile multipartFile){
        String originalFilename = multipartFile.getOriginalFilename();
        //获取源文件后缀
        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼装新文件名称
        String newFileName= UUID.randomUUID()+suffix;//UUID.randomUUID()随机字符串
        File file=new File(savePath+ newFileName);//    D:/images/jin.jpg
        try {
            //调用spring提供的方法进行文件读写
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newFileName;
    }
    /**
     * 通用下载方法
     * @param filename
     * @param response
     * @return
     */
    public static String downLoad(String filename,HttpServletResponse response){
        String filePath = "D:/images" ;
        File file = new File(filePath + "/" + filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/force-download");//MIME类型
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
           /* int i = bis.read(buffer);
            while(i != -1){
                os.write(buffer);
                i = bis.read(buffer);
            }*/
                int i=0;
                while((i = bis.read(buffer))!=-1){
                    os.write(buffer,0,i);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}

controller层代码

@Controller
@RequestMapping("news")
public class NewsController {
    @Autowired
    private NewsService newsService;
    private final ResourceLoader resourceLoader;
    @Autowired
    public NewsController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    //取出配置文件upload.path的值,赋给uploadPath类变量
    @Value(value = "${upload.path}")
    private String uploadPath;
    /**
     * 跳转添加
     * @return
     */
    @RequestMapping("toAdd")
    public String toAdd(){
        return "add";
    }
    @RequestMapping("add")
    public String add(Model model,@RequestParam Map map, @RequestParam MultipartFile pic){
        if(pic!=null){
            String newFilePath= FileUtil.uploadFile(uploadPath,pic);
            map.put("fileName",pic.getOriginalFilename());
            map.put("picPath",newFilePath);
        }
        int i=newsService.add(map);
        if(i>0){
            model.addAttribute("info","图片添加成功");
            return "redirect:list";
        }else{
            model.addAttribute("info","图片添加失败");
            return "redirect:list";
        }
    }
    /**
     * 新闻列表
     * @return
     */
    @RequestMapping("list")
    public String list(Model model){
        model.addAttribute("newsList",newsService.getList());
        return "list";
    }
    /**
     * 新闻删除
     */
    @RequestMapping("delete")
    public Object delete(Integer id){
        newsService.delete(id);
        return "forward:list";
    }
    /**
     * 新闻修改
     */
    @RequestMapping("toUpdate")
    public String toUpdate(Model model,Integer id){
        List<Map> listById = newsService.getListById(id);
        model.addAttribute("list",listById);
        return "edit";
    }
    @RequestMapping("update")
    public Object update(@RequestParam Map map,@RequestParam MultipartFile pic){
        System.out.println(map);
        String originalFilename = pic.getOriginalFilename();
        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName=UUID.randomUUID()+suffix;
        File file=new File(uploadPath+newFileName);
        try {
            pic.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put("picPath",newFileName);
        newsService.update(map);
        return "forward:list";
    }
    @RequestMapping("show")
    public ResponseEntity show(String fileName){
        try {
            // 由于是读取本机的文件,file是一定要加上的, path是在application配置文件中的路径
            return ResponseEntity.ok(resourceLoader.getResource("file:" + uploadPath + fileName));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    /**
     * 文件下载
     * @param fileName
     * @param response
     */
    @RequestMapping("/downLoad")
    public void downLoadFile(String fileName, HttpServletResponse response){
        FileUtil.downLoad(fileName,response);
    }
}

dao层代码

public interface NewsDao {
    /**
     * 获取新闻列表
     * @return
     */
    @Select(value = "select * from tb_news")
    List<Map> getList();

    /**
     * 新闻添加
     * @param map
     * @return
     */
    @Insert(value = "insert into tb_news values(seq_news_id.nextval,#{title},#{content},#{type},0,#{picPath})")
    int add(Map map);
    /**
     * 新闻删除
     */
    @Delete(value = "delete from tb_news where newsid=#{newsid}")
    int delete(int id);
    /**
     * 根据id获取新闻信息
     */
    @Select(value = "select * from tb_news where newsid=#{newsid}")
    List<Map> getListById(int id);
    /**
     * 更改新闻信息
     */
    @Update(value = "update tb_news set title=#{title},content=#{content},typeid=#{typeid},picpath=#{picPath} where newsid=#{newsid}")
    int update(Map map);
}

javaWeb文件上传和下载

标签:autowired   code   dao   tty   last   tps   header   web   interface   

原文地址:https://www.cnblogs.com/fantongxue/p/12443318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!