javaWeb文件上傳和下載

第一步

  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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章