天天看點

檔案、圖檔的上傳(一)-----前端與後端代碼

用的編譯器是idea,前端代碼在jsp頁面中,後端則是寫在SSM架構中控制層Controller。

前端代碼(jsp頁面)

<form action="${website}file/file/${id}" method="post" enctype="multipart/form-data">
        <input type='text'  name='textfield' id='textfield' class='txt' />
        <input type="file" name="file" class="file" id="fileField" 
size="28" onchange="document.getElementById('textfield').value=this.value" />
        <input type="submit"  name="submit" class="btn" value="上傳" />

    </form>
           

需要注意的是,form表單後面一定要加上

前端頁面展示:

檔案、圖檔的上傳(一)-----前端與後端代碼

點選浏覽,找到本地圖檔:

檔案、圖檔的上傳(一)-----前端與後端代碼

選擇打開,或輕按兩下,圖檔名稱就顯示在文本框中,點選上傳,即可将圖檔上傳到伺服器中,并将圖檔的相關資訊存儲在資料庫中。

後端代碼具體如下:

@RequestMapping(value = "/file/{id}", method = RequestMethod.POST)
   public String upload( @PathVariable("id") int id , @RequestParam("file")CommonsMultipartFile file, HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes) throws Exception {
        //獲得原始檔案名
        String filename = file.getOriginalFilename();
        System.out.println("原始檔案名:"+ filename);
        String newFileName =  UUID.randomUUID()+ filename;
//       UUID.randomUUID()局唯一辨別符,是指在一台機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的,
        ServletContext sc = request.getSession().getServletContext();
        String path = sc.getRealPath("image")+"/";
        File f = new File(path);
        if(!f.exists()){
            f.mkdirs();
        }
        if (!file.isEmpty()){
          try{
             FileOutputStream fos = new FileOutputStream(path+newFileName);
             InputStream in = file.getInputStream();
             int b = ;
             while((b = in.read())!=-){
                    fos.write(b);
                }
                fos.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        redirectAttributes.addAttribute("id",id);
        model.addAttribute("msg","上傳成功!");
        com.pandawork.common.entity.File file1 = new com.pandawork.common.entity.File();
        String name = "../../image/"+newFileName;
        file1.setName(name);
        file1.setVisible();
        fileService.addImage(file1);
        return "fileUpload";
    }
           

如果圖檔沒有上傳到你想要的目錄,你需要修改idea中預設的檔案上傳路徑。但是,怎麼修改呢,這是個問題。

自己嘗試了各種方法也沒有實作自己想要的結果,後來詢問了學長,知道了想要修改idea中檔案上傳到的路徑很簡單。

檔案、圖檔的上傳(一)-----前端與後端代碼

将此處路徑改為你需要的路徑即可。

String path = sc.getRealPath("image")+"/";
           

在後端代碼的這部分,如果你想上傳的檔案夾下沒有image檔案夾,則會自動建立image檔案夾,如果想在image檔案夾下另外再建一個名為memberImage的子檔案夾,則隻需将代碼改為

String path = sc.getRealPath("image/memberImage")+"/";
           

最後截了兩張關于檔案上傳的圖檔

檔案、圖檔的上傳(一)-----前端與後端代碼
檔案、圖檔的上傳(一)-----前端與後端代碼