• 上传图片或文件 方法一


     最近在巩固一些知识点,回过头看之前做过的项目,所以就在这里总结一下

    话不多说,直接看源码

    前端

    publish-menu.jsp

    1 <form action="PublishMenu" method="post" enctype="multipart/form-data" >
    2 
    3     <input name="menu_picture" type="file" id="file_input" style="display: none;" onchange="preImg(this.id,'photo_finish')" />
    4     <label for="file_input">
    5         <img id="photo_finish" src="img/finished_menu.jpg" width="210px" height="250px" style="margin-right: 20px;" />
    6     </label>
    7 
    8 </form>

    show-img.js

     1 function getFileUrl(sourceId) {
     2     var url;
     3     if(navigator.userAgent.indexOf("MSIE") >= 1) { // IE  
     4         url = document.getElementById(sourceId).value;
     5     } else if(navigator.userAgent.indexOf("Firefox") > 0) { // Firefox  
     6         url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
     7     } else if(navigator.userAgent.indexOf("Chrome") > 0) { // Chrome  
     8         url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
     9     }
    10     return url;
    11 }
    12 
    13 function preImg(sourceId, targetId) {
    14     var url = getFileUrl(sourceId);
    15     var imgPre = document.getElementById(targetId);
    16     imgPre.src = url;
    17 /*  alert("图片路径获取前!");
    18     var p = url.getPath(); //将图片的src变为获取到的路径
    19     alert("图片路径!" + p); */
    20 }

    后台

    package com.dgx.MenuShare.servlet;
    import
    java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.dl.MenuShare.service.MenuService; @SuppressWarnings("serial") public class PublishMenuServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {      // 设置请求对象以utf-8的形式接受表单数据 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8");int x = 0 ; int y = 0 ; String text[][] = new String[16][2] ; //准备用来存储其他非文件的信息 String img[][] = new String[9][2] ; //准备用来存储文件的信息 //新建上传工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); //设置文件大小限制。 //如果小于该文件限制,则文件直接保存在内存中 //如果大于该文件限制,则文件将保存到设置的临时目录中。 factory.setSizeThreshold(1024 * 1024); //getServletContext().getRealPath() 的用法 //比如s参数'/temp'表示根路径下的temp文件夹'返回一个File类型'你可以用判断它是否存在'不存在就建立'存在就用它 //设置临时目录 factory.setRepository(new File(getServletContext().getRealPath("/temp"))); //实例化一个ServletFileUpload对象用来上传 ServletFileUpload sfu = new ServletFileUpload(factory); //得到所有的表单项 List<FileItem> all = null; try { all = sfu.parseRequest(req); } catch (FileUploadException e) { e.printStackTrace(); } for(FileItem item : all) { //如果是普通表单字段 if(item.isFormField()) { //获得该字段名称 String name = item.getFieldName(); System.out.println("字段名称:"+name); //获得该字段值 String value = item.getString("utf-8"); System.out.println("字段值:"+value); text[x][0] = name ; text[x][1] = value ; System.out.println("数组text"+x+":"+text[x][0]+" "+text[x][1]); x++ ; //将值设置到request属性范围中 req.setAttribute(name, value); } //如果为文件域 else { //取得文件域字段名 String name = item.getFieldName(); System.out.println("文件域字段名:"+name); //取得文件名 String value = item.getName(); System.out.println("文件名:"+value); //截取文件名 int begin = value.lastIndexOf("\"); value = value.substring(begin + 1); img[y][0] = name ; if ( value!=null && value!="" ) { //将值设置到request属性范围中 req.setAttribute(name, value); //设置上传文件目录 String path = req.getRealPath("/"); //获取服务器下路径 path = path.replaceAll("\\", "/"); String uploadPath = path + "/upload" ; File file = new File(uploadPath); if (!file.exists()) { new File(uploadPath).mkdir(); }             //写入文件 try { if ( y==0 ) { item.write(new File(uploadPath,text[0][1]+".jpg")); img[y][1] = "upload/"+text[0][1]+".jpg" ; } else { item.write(new File(uploadPath,text[0][1]+"步骤"+y+".jpg")); img[y][1] = "upload/"+text[0][1]+"步骤"+y+".jpg" ; } System.out.println("数组img"+y+":"+img[y][0]+" "+img[y][1]); y++ ; } catch (Exception e) { e.printStackTrace(); } } else { img[y][1] = "" ; } } }

          ......

          String menu_picture = img[0][1] ;
          String picture_one = img[1][1] ; 
          ......
          MenuService menuService = new MenuService() ;

            把 图片文件路径 和其他信息 存进DB
            int i = menuService.AddMenuInfoService( ...... ) ;
            if ( i!=0 ) {
                req.setAttribute("massger", "上传图片文件成功");
            }
            else {
                req.setAttribute("massger", "上传图片文件失败"); 
         }
         //上传完成后执行跳转
         req.getRequestDispatcher("XXX.jsp").forward(req, resp);
      }
    }

    共同学习,共同进步,若有补充,欢迎指出,谢谢!

  • 相关阅读:
    第一次sprint团队贡献分改
    第一个Sprint冲刺事后诸葛报告
    第一个Sprint冲刺第十天
    第一个Sprint冲刺第九天
    第一个Sprint冲刺第八天
    第一个Sprint冲刺第七天
    第一个Sprint冲刺第六天
    第一个Sprint冲刺第五天
    第一个Sprint冲刺第四天
    第一个Sprint冲刺第三天
  • 原文地址:https://www.cnblogs.com/dengguangxue/p/10757601.html
Copyright © 2020-2023  润新知