• 重炉后-文件上传下载


    1.在springmvc.xml配置和文件中要加上

    1   <!-- 文件上传  富媒体解析器-->               
    2    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>     

    1.springmvc.xml代码如下

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
                            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
                            http://www.springframework.org/schema/mvc  
                            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  
                            http://www.springframework.org/schema/context  
                            http://www.springframework.org/schema/context/spring-context-3.2.xsd
                            http://www.springframework.org/schema/aop 
                            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd    
                            
                            
                            ">
    
        <!-- 扫描mvc -->
        <context:component-scan base-package="com.bypx.controller" />
        <aop:aspectj-autoproxy proxy-target-class="true" />
        <!-- 开启mvc注解功能 -->
        <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>text/plain;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                
            </mvc:message-converters>
        </mvc:annotation-driven>
        <!-- 视图解析器 -->
        <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!--前缀 -->
            <property name="prefix" value="" />
            <!--后缀 -->
            <property name="suffix" value="" />
            <property name="viewClass"
                value="org.springframework.web.servlet.view.JstlView" />
        </bean>
    
         <!-- 文件上传  富媒体解析器-->               
       <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>        
    
    
    </beans>

    2.在jsp页面的上传是一个按钮,然后按钮调用弹窗,在弹窗里面进行上传

    2.1这个是js代码,数据表格是在页面刷新后自动执行的,把文件上传放在一个弹窗里面是因为,如果单独一个按钮上传,他会提示说没有选择图片,而且这个弹窗里面还有2个隐藏的Input来接收前台传进来的2个id,把值赋值给隐藏Input框,然后再拿出来传到后台,这样就可以获取到uuid,进行文件上传所需要的主键了(PS:传uuid一直显示unfind的话,要记得在uuid两边再加上双引号并要用转义符,因为有可能uuid自动生成里面会有特殊字符所以要再加上双引号)

    $(function(){
        $('#sjb_div').datagrid({   
            title:"文件管理",
            url:'../../UploadController/cakan.do',    
            pagination:true,
            toolbar:"#gongjulan",
            columns:[[    
                      {field:'up_uuid',title:'文件编号',align:'center'},    
                      {field:'us_name',title:'用户名',align:'center'},    
                      {field:'us_phone',title:'联系方式',align:'center'},    
                      {field:'up_name',title:'文件名',align:'center'},    
                      {field:'wjus_srid',title:'用户id',align:'center'},    
                      {field:'up_type',title:'文件分类',align:'center',formatter: function(value,row,index){
                          if (value==0){
                              return "加工文件";
                          } else if(value==1){
                              return "订单文件";
                          }
                      }
                      },    
                      {field:"up_shangchuan",title:'文件',align:'center',formatter: function(value,row,index){
                          if (row.up_name==null||row.up_name==""){
                              return "<a onclick='wjshangchuan(""+row.wjus_srid+"",""+row.up_uuid+"")' class='easyui-linkbutton' data-options='iconCls:'icon-add' style='color:blue'  ><u>上传</u></a>";
                          } else {
                              return "<a onclick='wjshangchuan(""+row.wjus_srid+"",""+row.up_uuid+"")' class='easyui-linkbutton' data-options='iconCls:'icon-add' style='color:blue'  ><u>替换</u></a>" +
                              "&nbsp;&nbsp; <a href='../../FileController/download.do?fileName="+row.up_name+"' onclick=wjxiazai(""+row.up_name+"")>下载</a>";
                          }
                      }
                      },
                      ]]
        }); 
    });

    2.2点击上传后调用的方法(把获取到的2个主键分别存到2个隐藏的input里面)把弹窗打开:

    //文件上传按钮static-----------------------------------------------------------------------------
    function wjshangchuan(uuid,up_ud){
        document.getElementById("us_yingchang_input").value=uuid;//把值赋给隐藏input
        document.getElementById("up_yingchang_input").value=up_ud;//把值赋给隐藏input
        $('#wjshangchuan_div').dialog('open');    
    }
    //文件上传按钮end-----------------------------------------------------------------------------

    2.3这个是弹窗(弹窗里面有2个隐藏input框用来接收值)

    <!-- 文件下载start--------------------------------------------------- -->
        <div id="wjshangchuan_div" class="easyui-dialog" title="上传"
            style="400px;height:200px; top:150px"
            data-options="iconCls:'icon-save',resizable:true,modal:true,closed:true">
            <form id="upload_form" method="post" enctype="multipart/form-data">
                <input typx="text" id="us_yingchang_input" type="hidden"> <input
                    typx="text" id="up_yingchang_input" type="hidden"> <input
                    type="file" name="uploadfile" /> <input type="button"
                    onclick="wj_shangchuan()" value="上传" />
            </form>
        </div>
        <!-- 文件下载end--------------------------------------------------- -->

    2.4这个是上传文件的js(先拿到隐藏input框里面的值,然后把跟路径一起传到后台去)

    //文件上传static-----------------------------------------------------------------------------
    function wj_shangchuan(){
        var zhi= $("#us_yingchang_input").val();//获取隐藏input值
        var up_uuid= $("#up_yingchang_input").val();//获取隐藏input值
        var attname;
        var path;
        var formData = new FormData($("#upload_form")[0]);
        $.ajax({
            url: '../../FileController/uploadFileCustmer.do?type=0&&uuid='+zhi+'&&up_uuid='+up_uuid,
            type: 'POST',
            data: formData,
            async: false,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function (returndata) {
                path = returndata.path;
                attname = returndata.oname;
                if(path==null||attname==null){
                    $.messager.alert('警告','请选择要上传的文件'); 
                }else{
                    $.messager.alert('提示','附件上传成功!!!'); 
                }
                $('#sjb_div').datagrid('reload');  //重载数据表
                $("#wjshangchuan_div").dialog('close');//关闭弹窗
            },
            error: function (returndata) {
    
            }
        });
    }
    //文件上传end-----------------------------------------------------------------------------

    2.5图片展示:

     

    2.6弹窗里面的<form>表单要注意,文件上传的name,要和等等接下来的Controoler里面的 multipartResolver 对象的名字要一样,不然会找不到我们选择的文件,这个要注意

    <!-- 文件下载start--------------------------------------------------- -->
    
    <form id="upload_form" method="post" enctype="multipart/form-data">
       <input type="file" name="uploadfile" />
       <input type="button" onclick="wj_shangchuan()" value="上传" />
            </form>
        </div>
        <!-- 文件下载end--------------------------------------------------- -->

    2.7:补2.6的图

    3.FileController

    package com.bypx.controller;
    
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.activation.FileTypeMap;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.apache.commons.io.FileUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    import com.bypx.page.UploadPage;
    import com.bypx.page.UserPage;
    import com.bypx.util.DateEasy;
    import com.bypx.util.DeleteFileUtil;
    import com.bypx.util.EnvironmentUtil;
    import com.bypx.util.JsonUtil;
    import com.bypx.util.KeyGenerate;
    import com.bypx.util.StringUtil;
    
    @Controller
    @RequestMapping("FileController")
    public class FileController {
        @Autowired
        private JdbcTemplate jdbcTemplate;
        @RequestMapping("uploadFileCustmer")
        @ResponseBody
        public String uploadFileCustmer(HttpServletRequest request,MultipartFile uploadfile, HttpSession session,UserPage page,UploadPage up_page) throws IOException {
            // 1获得上传的文件内容
            byte[] bytes = uploadfile.getBytes();
            System.out.println(bytes+"..................47");
            // 2获得upload的绝对路径
            String path =EnvironmentUtil.getInstance().getAppPath()+"upload/";
            String path2="upload/";
            System.out.println(path+"-----------------45-----path");
            System.out.println(uploadfile.getOriginalFilename()+"-------49------");
            // 3在服务器的upload目录下创建File对象
    
            if (uploadfile.getOriginalFilename() != "" && uploadfile.getOriginalFilename() != null) {
                String time = new DateEasy().toYYYYMMDDHHMMSS();// 加随机数,防止重复
                System.out.println(time+"----------54-------");
                String extname="";
                if(uploadfile.getOriginalFilename().indexOf(".")!=-1){
                    extname=uploadfile.getOriginalFilename();
                }
                String oname = time+"_" +extname;  // 上传文件的原始名字
                System.out.println(oname+"..........60..........");
                File file = new File(path, oname);
                System.out.println(file+".......62.........");
                // 4将上传的文件拷贝到指定的目录
                try {
                    FileUtils.writeByteArrayToFile(file, bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Map<String, String> mm = new HashMap<String, String>();
                mm.put("path", "upload/");
                mm.put("oname", oname);
                String wuuidString=request.getParameter("uuid");
                System.out.println(wuuidString+"+++++.....74");
                System.out.println(oname+"............................");
    //            String sql="INSERT INTO sk_upload(UUID,up_name,up_path,TYPE,SRID) VALUE(?,?,?,?,?)";
    //          jdbcTemplate.update(sql,KeyGenerate.getKey(),oname,path2,request.getParameter("type"),request.getParameter("uuid"));
                String sql="UPDATE sk_upload SET up_name=?,up_path=?,TYPE=?,SRID=? WHERE UUID=? ";
                jdbcTemplate.update(sql,oname,path2,request.getParameter("type"),request.getParameter("uuid"),request.getParameter("up_uuid"));
                System.out.println(oname+"............81");
                System.out.println(path2+"............82");
                System.out.println(request.getParameter("type")+"............83");
                System.out.println(request.getParameter("uuid")+"............84");
                System.out.println(request.getParameter("up_uuid")+"............86");
                System.out.println(sql+"++++++++++++++++++++++++++");
                System.out.println(mm+"........75...............");
                return JsonUtil.toJson(mm);
            } else {
                Map<String, String> mm2 = new HashMap<String, String>();
                mm2.put("path", null);
                mm2.put("oname", null);
                return JsonUtil.toJson(mm2);
            }
        }
    
        @RequestMapping("uploadFile")
        @ResponseBody
        public String uploadFile(HttpServletRequest request, @RequestParam("uploadfile") CommonsMultipartFile uploadfile, HttpSession session) throws IOException {
            // 1获得上传的文件内容
            byte[] bytes = uploadfile.getBytes();
            // 2获得upload的绝对路径
            String path = "upload/";
            // 3在服务器的upload目录下创建File对象
    
            if (uploadfile.getOriginalFilename() != "" && uploadfile.getOriginalFilename() != null) {
                String time = new DateEasy().toYYYYMMDDHHMMSS();// 加随机数,防止重复
                String extname="";
                if(uploadfile.getOriginalFilename().indexOf(".")!=-1){
                    extname=uploadfile.getOriginalFilename().substring(uploadfile.getOriginalFilename().lastIndexOf("."));
                }
                String oname = time +extname;  // 上传文件的原始名字
                File file = new File(path, oname);
                // 4将上传的文件拷贝到指定的目录
                try {
                    FileUtils.writeByteArrayToFile(file, bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Map<String, String> mm = new HashMap<String, String>();
                mm.put("path", path);
                mm.put("oname", oname);
                String uuid = request.getParameter("uuid");
                Map<String,Object> filepathm=new HashMap<String, Object>();
                //以前有文件就要把以前的文件删除掉
                try{
                    String oldpathsql="select photo_path from jxc_yl where uuid=?";
                    filepathm=jdbcTemplate.queryForMap(oldpathsql, uuid);
                }catch(Exception e){}
                String filepath=filepathm.get("photo_path")+"";
                //找到以前的路径如果不等于null
                if(!StringUtil.zNull(filepath).equals("")){
                    DeleteFileUtil.deleteFile(EnvironmentUtil.getInstance().getAppPath()+filepath);
                }
                return JsonUtil.toJson(mm);
            } else {
                Map<String, String> mm2 = new HashMap<String, String>();
                mm2.put("path", null);
                mm2.put("oname", null);
                return JsonUtil.toJson(mm2);
            }
        }
        @RequestMapping("clearfile")
        @ResponseBody
        public Map<String,Object> clearfile(String uuid,String filepath){
                Map<String,Object> mm=new HashMap<String, Object>();
                if(StringUtil.zNull(filepath).equals("")){
                    mm.put("success", "donothing");
                    return mm;
                }
                String sql="select count(*) as total from jxc_yl where uuid=?";
                int nn=jdbcTemplate.queryForInt(sql,uuid);
                boolean doo=false;
                if(nn==0){
                    System.out.println(EnvironmentUtil.getInstance().getAppPath()+"upload/"+filepath);
                    doo=DeleteFileUtil.deleteFile(EnvironmentUtil.getInstance().getAppPath()+"upload/"+filepath);
                }
                
                if(doo==true){
                    mm.put("success", "do");
                }else{
                    mm.put("success", "donothing");
                }
                return mm;
        }
    
        /***
         * 实现文件下载
         * 
         * @throws UnsupportedEncodingException
         * ***/
        @RequestMapping("/download")
        public String downloadFile(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) {
            String path = request.getSession().getServletContext().getRealPath("\upload");
            System.out.println(path+"+++++++++168");
            if (fileName != null) {
                try {
                    fileName=java.net.URLDecoder.decode(fileName,"utf-8");
                    System.out.println(fileName+"++++++++99999999999");
                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                fileName = path+"\"+fileName;
                System.out.println(fileName+"++++++++99999999999");
                File file = new File(fileName);
                System.out.println(file+"........171");
                System.out.println(file.exists()+".......172");
                if (file.exists()) {
                    byte[] buffer = new byte[1024];
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    try {
                        response.setContentType("application/force-download");// 设置强制下载不打开
                        response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("gbk"), "iso-8859-1"));// 设置文件名
    
                        fis = new FileInputStream(file);
                        System.out.println(fis+"--------182");
                        bis = new BufferedInputStream(fis);
                        System.out.println(bis+"--------184");
                        OutputStream os = response.getOutputStream();
                        int i = bis.read(buffer);
                        while (i != -1) {
                            os.write(buffer, 0, i);
                            i = bis.read(buffer);
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    } finally {
                        if (bis != null) {
                            try {
                                bis.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
            return null;
        }
    }
    --------------------------------------------------------------------分界线----------------------------------------------------------------------------------------------------------------------------------------------

    4.文件下载

    文件下载和前面文件上传是差不多了,文件下载的Controller和上传的在一起就不贴图了,就贴一下按钮(文件下载不需要选择,所以只需一个按钮就好,所以就用了herf)

  • 相关阅读:
    ajax 拼接html标签 thinkphp
    使用Log4J进行日志操作
    学习Spark2.0中的Structured Streaming(一)
    互联网日志实时收集和实时计算的简单方案
    Integer.valueOf方法的源码解读
    spark的ML和MLLib两个包区别和联系?
    数组和集合区别
    Java中的集合类
    Spark会把数据都载入到内存么?
    可变参数
  • 原文地址:https://www.cnblogs.com/likeji/p/7182732.html
Copyright © 2020-2023  润新知