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>

 

转载于:https://www.cnblogs.com/stepbystepwhx/p/7782782.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值