1. 程式人生 > >SpringMVC讀取本地圖片和上傳圖片

SpringMVC讀取本地圖片和上傳圖片

/**
     * 獲取本地圖片
     * @param pictureName //檔名
     * @return
     */
    @RequestMapping("/picReq")
    public void ShowImg(String pictureName, HttpServletRequest request, HttpServletResponse response) throws IOException{
        //檔名
        String imgFile = request.getParameter("imgFile");
        //這裡是存放圖片的資料夾地址
String path= "F:/DreamCinemaImg"; FileInputStream fileIs=null; OutputStream outStream = null; try { fileIs = new FileInputStream(path+"/"+pictureName); //得到檔案大小 int i=fileIs.available(); //準備一個位元組陣列存放二進位制圖片 byte data[]=new
byte[i]; //讀位元組陣列的資料 fileIs.read(data); //設定返回的檔案型別 response.setContentType("image/*"); //得到向客戶端輸出二進位制資料的物件 outStream=response.getOutputStream(); //輸出資料 outStream.write(data); outStream.flush(); }
catch (Exception e) { logger.info("系統找不到影象檔案:"+path+"/"+imgFile); return; }finally { //關閉輸出流 outStream.close(); //關閉輸入流 fileIs.close(); } }

SpringMVC上傳檔案

1、首先先匯入spring相關的依賴

2、匯入檔案上傳的依賴

<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
</dependency>

3、springmvc配置檔案新增上傳檔案的配置

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 限制檔案上傳的總大小(單位:位元組),不配置此屬性預設不限制 -->
        <property name="maxUploadSize" value="1048576000000"/>
        <!--指定檔案寫入記憶體的大小-->
        <property name="maxInMemorySize" value="1048576000"/>
        <!-- 設定檔案上傳的預設編碼-->
        <property name="defaultEncoding" value="utf-8"/>
</bean>

4、程式碼

/**
     * 圖片上傳
     * @param file
     * @param picNum
     * @return
     */
    @RequestMapping("/uploadPic")
    @ResponseBody
    public ResponseView  addProduct(MultipartFile file, Integer picNum){
        ResponseView rv = new ResponseView();
        //構建檔案目錄
        File uploadDir = new File("F:/DreamCinemaImg");
        //如果目錄不存在,則建立
        if(!uploadDir.exists()){
            uploadDir.mkdir();
        }
        //獲取上傳的檔名
        String fileName = file.getOriginalFilename();
        //構建一個完整的檔案上傳物件
        File uploadFile = new File(uploadDir.getAbsolutePath() + "/" + fileName);
        //判斷檔案是否存在
        if(!uploadFile.exists()) {
            try {
                //通過transferTo方法進行上傳
                file.transferTo(uploadFile);
                rv.setCode(0);
                //把檔名放入響應檢視
                rv.setData(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                rv.setCode(500);
                throw new RuntimeException(e.getMessage());
            }
        }else{
            rv.setCode(400);
        }
        return rv;
    }