1. 程式人生 > >關於圖片,pdf上傳,預覽,下載

關於圖片,pdf上傳,預覽,下載

       其實 上傳照片跟上傳pdf 還有其他 影音類的檔案差不多  就是jsp 頁面上顯示的方式不一樣

       廢話不多說,直接上程式碼

      1. 上傳檔案  首先有個上傳檔案的按鈕

       

其 程式碼為:


<div class="control-group">
<label class="control-label">上傳pdf檔案:</label>
<div class="controls">
     <input style="width:200px" class="g-file" type="file" name="pictureFile" accept=".pdf" name="file"                                   size="chars"  value="請上傳"/> 
<span class="help-inline"><font color="red"></font> </span>
</div>
</div>

2.設定form表單  


  1. <form:form id="inputForm" modelAttribute="article" action="${ctx}/cms/article/save"  
          method="post" enctype="multipart/form-data" class="form-horizontal">

3.實體類 兩個必要的屬性    ①接受檔案   ②儲存檔名(相當於檔案的地址)

  資料庫中只需要  一個欄位儲存路徑即可


4.controller 層


  1. @RequestMapping(value = "save")
    public String save(Article article, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
    try {
    //判斷檔案是否為空
    if (!article.getPictureFile().isEmpty()) {  
                try {  
                //1. 獲取完整名稱
                String fileStr = article.getPictureFile().getOriginalFilename();
        //2. 使用隨機生成的字串+源圖片副檔名組成新的圖片名稱,防止圖片重名
        String newfileName = IdGen.uuid().toString() + fileStr.substring(fileStr.lastIndexOf("."));
                    // 儲存的檔案路徑(如果用的是Tomcat伺服器,檔案會上傳到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\資料夾中  )  
                    String filePath = request.getSession().getServletContext().getRealPath("/") 
                    + "issueimage/" +newfileName; 
                    System.err.println(filePath);  
                    File saveDir = new File(filePath);  
                    if (!saveDir.getParentFile().exists())  
                        saveDir.getParentFile().mkdirs();  
                    System.err.println(filePath);  
                    article.getPictureFile().transferTo(saveDir);  
                    //article.setArchiveAddress(newfileName);
                    String archive_address=newfileName;  //地址路徑
                    if(article.getId()==null||article.getId().equals("")) {
                    article.setId(IdGen.uuid());
                    article.setIsNewRecord(true);
                    article.setCreatePeo(UserUtils.getUser().getId());
                    article.setAddress(archive_address);
                    addMessage(redirectAttributes, "新增文章成功!");
                    }else {
                    article.setIsNewRecord(false);
                    addMessage(redirectAttributes, "修改文章成功!");
                    }

5.jsp 顯示方式


照片顯示   :