1. 程式人生 > >在本機上傳和下載圖片

在本機上傳和下載圖片

第一步

  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);
}