Java web項目 上傳圖片保存到數據庫,並且查看圖片,(從eclipse上移動到tomact服務器上,之路徑更改,包括顯示圖片和導出excel)


//項目做完之后,在本機電腦運行完全正常,上傳圖片,顯示圖片,導出excel,讀取excel等功能,沒有任何問題,但是,當打成war包放到服務器上時,這些功能全部不能正常使用。

最大的原因就是,本機測試跟服務器上的路徑發生了變化。

記錄一下,上傳圖片和顯示圖片的代碼

1.前端頁面:

<form action="${pageContext.request.contextPath}/UploadWeiXiuServlet"
                enctype="multipart/form-data" method="post">

<input type="file" name="file" multiple="multiple" align="center">
                <input type="submit" value="提交" />
</form>

2:后台servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log.info("上傳維修圖片附件的servlet");
        request.setCharacterEncoding("utf-8");  
        response.setContentType("text/html;charset=utf-8");  
       
        String path = request.getSession().getServletContext().getRealPath(  
                "/upload/weixiuimg");
        
        File filemulu =new File(path);    
      //如果文件夾不存在則創建    
      if  (!filemulu .exists())      
      {       
          System.out.println("//不存在");  
          filemulu .mkdir();    
      } else   
      {  
          System.out.println("//目錄存在");  
      }  
        log.info("路徑:"+path);
        Map<String, String> map = Upload.upload(request, 1024 * 1024 * 10, path);  
        String file= map.get("file"); // 名稱  
       // String newFile = map.get("newFile");// 地址  
        MuJUService mjService = new MuJUService();
        //System.out.println(map.get("type"));
        boolean flag=mjService.uploadImg("upload/weixiuimg/"+file,map.get("wx_id"));//調用方法,存到數據庫
        HttpSession session=request.getSession();
        if (flag) {
            log.info("圖片上傳成功");
            session.setAttribute("flag", "上傳成功");
        }else {
            log.info("圖片上傳失敗");
            session.setAttribute("flag", "上傳失敗");
        }
        
    

3.upload類

 

public static Map<String, String> upload(HttpServletRequest request,
            int maxSize, String path) {
        //以map形式保存數據 key對應保存的是獲取界面上的name名稱 value保存的是獲取界面上的name對應的值
        Map<String, String> map = new HashMap<String, String>();
        Part part = null;
        try {
            MultipartParser mrequest = new MultipartParser(request, maxSize);
            mrequest.setEncoding("utf-8");
            //遍歷所有的part組
            while ((part = mrequest.readNextPart()) != null) {
                if (part.isFile()) {  //判斷是否是文件
                    FilePart filepart = (FilePart) part;//轉化成文件組
                    String fileName = filepart.getFileName();//得到文件名
                    if (fileName != null && fileName.length() > 0) {
                        // 取得擴展名
                        String fileExtName = fileName.substring(
                                fileName.lastIndexOf(".") + 1).toLowerCase();
                        // 只上傳圖片  //判斷圖片上傳的格式是否符合 后綴名是否有效
                        if (fileExtName.equalsIgnoreCase("jpeg")
                                || fileExtName.equalsIgnoreCase("png")||
                                fileExtName.equalsIgnoreCase("jpg")
                                || fileExtName.equalsIgnoreCase("gif")
                                || fileExtName.equalsIgnoreCase("ico")
                                || fileExtName.equalsIgnoreCase("bmp")
                                || fileExtName.equalsIgnoreCase("flv")
                                || fileExtName.equalsIgnoreCase("mp4")
                                || fileExtName.equalsIgnoreCase("mp3")) {

                            /*String newFileName = new Date().getTime() + "."+ fileExtName;//重新改文件名  文件名+擴展名 */                             
                            String newFileName =new Date().getTime() +fileName;//不改圖片名字
                            String newPath = path + "/" + newFileName; //文件處理文件上傳的路徑
                            File newFile = new File(newPath);
                            filepart.writeTo(newFile);  //將文件真正寫入到對應的文件夾中
                            //filepart.getName()  得到 request 要接收的參數的名字
                            map.put(filepart.getName(), newFileName);//把文件信息保存到map中
                            map.put("newFile", newFile.toString());
                        } else {
                            map.put("geshi", "geshi");
                            continue;
                        }// 說明上傳的不是圖片
                    } else {
                      map.put("yes","yes");
                        continue; // 說明沒有選擇上傳圖片
                    }
                } else if (part.isParam()) {  //判斷是否是參數
                    ParamPart paramPart = (ParamPart) part;
                    map.put(paramPart.getName(), paramPart.getStringValue());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

 

4.顯示圖片,前端  jquery----彈框bootstrap,模態框傳值

        
////request.getScheme()得到的:http:loaclhost:8888/
在eclipse中測試的時候可能只要得到 String path =request.getContextPath();---/muju_pro(項目名),在拼接上數據庫中圖片的url就可以取到了,
但是在服務器上必須是Http:10.1.10.114:8888.。。。。這樣的路徑。

<%
String path =request.getContextPath(); String realpath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> //綁定模態框展示的方法 $('#portrait1').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) // 觸發事件的按鈕 var recipient = button.data('whatever') // 解析出whatever內容 var modal = $(this) //獲得模態框本身 //更改將title的text // alert("C:/Program Files/Apache Software Foundation/Tomcat 7.0/webapps/muju_pro/"+recipient); /* modal.find('.modal-body img').attr("src",recipient); */ modal.find('.modal-body img').attr("src","<%=realpath%>/"+recipient); })

html

<div class="modal fade" id="addSource" role="dialog" aria-labelledby="gridSystemModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="gridSystemModalLabel">修改圖片</h4>
                        
                    </div>
                    <div class="modal-body">
                        <div class="container-fluid">
                            <form class="form-horizontal" action="${pageContext.request.contextPath}/UploadWeiXiuServlet"
                enctype="multipart/form-data"     method="post"><!--  -->
                                <div class="form-group">
                                    <label for="sLink" class="col-xs-3 control-label">上傳圖片:</label>
                                    <div>
                                    <input type="hidden" id="wx_id2" name="wx_id"/>
                                    <input type="hidden" value="xiugai" name="type"/>
                                    <input type="file" name="file" multiple="multiple" align="center">
                                    <input type="submit" value="提交" />
                                    </div>
                                    <div class="col-xs-8 ">
                                        <input type="hidden" id="wx_id" name="wx_id">
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-xs btn-xs btn-white" data-dismiss="modal">取消下單</button>
                    </div>
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM