zoukankan      html  css  js  c++  java
  • 文件的上传下载

    一、servlet基本方式(servlet3.0以上)

     下面是工程的大致目录结

    upload.jsp

    <%-- start --%>
    
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <form action="test.do" enctype="multipart/form-data" method="post">
    <input type="file" name="file"> <br>
    
    <input type="submit" name="提交"> 
    </form>
    </body>
    </html>
    
    
    
    <%-- end --%>

    Download.java

    package com.upload;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    
    //location表示文件缓存的位置
    @MultipartConfig(location="D:/temp")
    //定义servlet访问方式,对应web.xml
    @WebServlet(loadOnStartup = 1, initParams = { @WebInitParam(name = "test", value = "test") }, urlPatterns = "/test.do")
    public class Upload extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
        
        private String test = "";
    
        @Override
        public void init(ServletConfig config) throws ServletException {
            test = config.getInitParameter("test");
            System.out.println(test);
        }
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            Part part = req.getPart("file");
            String info = part.getHeader("Content-Disposition");
            String fileName = info.substring(info.indexOf("filename="") + 10, info.lastIndexOf("""));
            //System.out.println(fileName);
            //part.write(fileName);
            resp.setContentType("application/x-msdownload");
            resp.addHeader("Content-Disposition", "attachment; filename="" + fileName + """);
            InputStream inputStream = part.getInputStream();
            byte[] buff = new byte[1024];
            OutputStream outputStream = resp.getOutputStream();
            while((inputStream.read(buff)) != -1) {
                outputStream.write(buff);
            }
            
        }
    
    }

    Upload.java

    package com.upload;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    
    //loaction定义要保存文件的路径
    @MultipartConfig(location="D:/temp")
    @WebServlet(loadOnStartup = 1, initParams = { @WebInitParam(name = "test", value = "test") }, urlPatterns = "/download.do")
    public class Download extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
        
        private String test = "";
    
        @Override
        public void init(ServletConfig config) throws ServletException {
            test = config.getInitParameter("test");
            System.out.println(test);
        }
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            Part part = req.getPart("file");
            String info = part.getHeader("Content-Disposition");
            String fileName = info.substring(info.indexOf("filename="") + 10, info.lastIndexOf("""));
            System.out.println(fileName);
            part.write(fileName);
            
        }
    
    }

    由于使用的是注释的方式注册servlet,所以web.xml没有注册信息

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
      <display-name>uploadAndDownload</display-name>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    启动tomcat,输入网址localhost:8080/uploadAndDownload/upload.jsp进行测试。

    二、smartupload

    需要下载smartupload的jar包


    jsp页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <form action="SUpload" method="post" enctype="multipart/form-data">
        <input type="file" name="file1"><br>
        <input type="file" name="file2"><br>
        <input type="file" name="file3"><br>
        
        <input type="submit" value="submit">
    </form>
    </body>
    </html>

    SUpload.java

    package youth.hong;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.jspsmart.upload.Files;
    import com.jspsmart.upload.SmartUpload;
    
    @SuppressWarnings("serial")
    public class SUpload extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            SmartUpload smartUpload = new SmartUpload();
            smartUpload.initialize(this.getServletConfig() , req, resp);
            String filePath = "D:/temp";
            smartUpload.setMaxFileSize(1024*1024*10);
            smartUpload.setTotalMaxFileSize(1024*1024*30);
            smartUpload.setAllowedFilesList("txt,jpg,jpeg,gif");
            try {
                //smartUpload.setDeniedFilesList("exe");
                //准备上传
                smartUpload.upload();
                //上传并返回上传成功的个数
                smartUpload.save(filePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            Files files = smartUpload.getFiles();
            
            for(int i = 0; i < files.getCount(); i++) {
                System.out.println("-------------------------");
                System.out.println("表单中的字段名:" + files.getFile(i).getFieldName());
                System.out.println("文件名:" + files.getFile(i).getFileName());
                System.out.println("文件路径名:" + files.getFile(i).getFilePathName());
                System.out.println("文件的大小:" + files.getFile(i).getSize());
                System.out.println("-------------------------");
            }
        
            
        }
    
        
        
    }

     下载

    Download.java

    package youth.hong;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @SuppressWarnings("serial")
    public class Download extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String fileName = req.getParameter("fileName");
            String path = "D:/" + fileName;
            File file = new File(path);
            InputStream inputStream = new FileInputStream(file);
            byte[] buff = new byte[inputStream.available()];
            OutputStream outputStream = resp.getOutputStream();
            resp.setContentType("application/x-msdownload");
            resp.addHeader("Content-Disposition", "attachment; filename="" + fileName + """);
            inputStream.read(buff);
            outputStream.write(buff);
            inputStream.close();
            outputStream.close();
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
        
        
        
    }

    批量下载

    BatchDownload.java

    package youth.hong;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @SuppressWarnings("serial")
    public class BatchDownload extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            
            String[] fileNames = req.getParameterValues("fileName");
            
            String filePath = "D:/temp/";
            
            
            
            resp.setContentType("application/x-msdownload");
            resp.addHeader("Content-Disposition", "attachment; filename="hello.zip"");
            
            ZipOutputStream zip = new ZipOutputStream(resp.getOutputStream());
            
            for (String fileName : fileNames) {
                File file = new File(filePath + fileName);
                //用于区分单个文件
                ZipEntry zipEntry = new ZipEntry(fileName);
                zip.putNextEntry(zipEntry);
                
                FileInputStream read = new FileInputStream(file);
                byte[] buff = new byte[1024];
                
                while((read.read(buff)) != -1) {
                    zip.write(buff);
                }
                
                zip.flush();
                zip.setComment("下载的项目:" + fileName +"
    " );
                read.close();
            }
            
            
            zip.closeEntry();
            zip.close();
            
            
        }
    
        
        
    }

     web.xml配置

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
      <display-name>scxz</display-name>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      
      <servlet>
          <servlet-name>upload</servlet-name>
          <servlet-class>youth.hong.Upload</servlet-class>
      </servlet>
      
      <servlet-mapping>
          <servlet-name>upload</servlet-name>
          <url-pattern>/upload</url-pattern>
      </servlet-mapping>
      
       <servlet>
          <servlet-name>download</servlet-name>
          <servlet-class>youth.hong.Download</servlet-class>
      </servlet>
      
      <servlet-mapping>
          <servlet-name>download</servlet-name>
          <url-pattern>/download</url-pattern>
      </servlet-mapping>
      
       <servlet>
          <servlet-name>SUpload</servlet-name>
          <servlet-class>youth.hong.SUpload</servlet-class>
      </servlet>
      
      <servlet-mapping>
          <servlet-name>SUpload</servlet-name>
          <url-pattern>/SUpload</url-pattern>
      </servlet-mapping>
      
      <servlet>
          <servlet-name>BatchDownload</servlet-name>
          <servlet-class>youth.hong.BatchDownload</servlet-class>
      </servlet>
      
      <servlet-mapping>
          <servlet-name>BatchDownload</servlet-name>
          <url-pattern>/BatchDownload</url-pattern>
      </servlet-mapping>
    </web-app>

    使用富文本上传文件

    到http://kindeditor.codeplex.com/下载

    jsp页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>MultiImageDialog Examples</title>
    <link rel="stylesheet" href="css/themes/default/default.css" />
    <script src="js/kindeditor.js"></script>
    <script src="js/lang/zh_CN.js"></script>
    <script>
        var editor;
        KindEditor.ready(function(K) {
            editor = K.create('textarea[name="content"]', {
                allowFileManager : true,
           //设置上传文件的路径 uploadJson :
    '/KindEditorSCXZ/uploadImg' }); }); </script> </head> <body> <textarea name="content" style="800px;height:400px;visibility:hidden;">KindEditor</textarea> </body> </html>

    upload.java

    package com.upload;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    
    @MultipartConfig(location = "D:\newworkspace20160818\KindEditorSCXZ\WebContent\images")
    @WebServlet(urlPatterns = "/uploadImg")
    public class Upload extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //    Collection<Part> parts = req.getParts();
            /**
             * 由于富文本是使用多次请求进行上传操作的,所以不存在一次请求有多个文件同时上传的问题
             */
            String filename = "";
            //富文本上传时的文件域名
            Part part = req.getPart("imgFile");
            String info = part.getHeader("Content-Disposition");
            System.out.println(info);
            filename = info.substring(info.indexOf("filename="") + 10, info.lastIndexOf("""));
            /*for (Part part : parts) {
                String info = part.getHeader("Content-Disposition");
                filename = info.substring(info.indexOf("filename="" + 10), info.lastIndexOf("""));
                part.write(filename);
            }*/
            part.write(filename);
            resp.setContentType("application/json;charset=utf-8");
            PrintWriter pw = resp.getWriter();
            pw.write("{"error":0, "url":"/KindEditorSCXZ/images/" + filename + ""}");
        }
    
    }

     使用springMVC上传下载

    UploadDownload.java

    package youth.hong.annotation;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Date;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.UUID;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    import org.springframework.web.multipart.commons.CommonsMultipartResolver;
    import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
    
    @Controller
    @RequestMapping("/upload")
    public class UploadDownloadController extends MultiActionController {
        
        @RequestMapping("/file")
        public String uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response){
            
            InputStream in = null;
                    
            OutputStream out = null;
            
            System.out.println("文件名:" + file.getOriginalFilename() + "---------" + file.getContentType() + "----------" + file.getSize());
            
            long start = System.currentTimeMillis();
            
            if(!file.isEmpty()) {
                
                try {
                    in = file.getInputStream();
                    
                    out = new FileOutputStream("D:/" + new Date().getTime() + file.getOriginalFilename());
                    
                    byte[] buff = new byte[1024];
                    
                    while((in.read(buff)) != -1) {
                        out.write(buff);
                        out.flush();
                    }
                    
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if(in != null) {
                            in.close();
                        }
                        if(out != null) {
                            out.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    
                }
            }
            
            long end = System.currentTimeMillis();
            
            System.out.println("传统java上传用时:" + (end - start));
            
            return "/fileupload";
        }
        
        
        
        @RequestMapping("/file2")
        public String uploadFile2(HttpServletRequest request, HttpServletResponse response){
            //拿到文件上传解析器
            CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getServletContext());
            //传统的java解析request是否为上传文件,这个与xml配置的解析器是一样的。
            if(resolver.isMultipart(request)) {
                
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
                //键值对的形式
                Map<String, MultipartFile> map = multipartRequest.getFileMap();
                
                Set<Map.Entry<String, MultipartFile>> set = map.entrySet();
                
                for (Entry<String, MultipartFile> entry : set) {
                    
                    MultipartFile file = entry.getValue();
                    
                    String fileName = "demo" + UUID.randomUUID() + "." + file.getOriginalFilename().split("\.")[1];
                    
                    File f = new File("D:/" + fileName);
                    
                    try {
                        long start = System.currentTimeMillis();
                        //将文件输出
                        file.transferTo(f);
                        long end = System.currentTimeMillis();
                        
                        System.out.println("springMVC 上传用时:" + (end - start));
                    } catch (IllegalStateException | IOException e) {
                        e.printStackTrace();
                    }
                    
                    System.out.println("ok!!");
                }
                
            }
            
            return "/fileupload";
        }
        
        @RequestMapping("/file3")
        public String uploadFile3(MultipartFile[] multipartFile) throws Exception {
            
            
            for (MultipartFile file : multipartFile) {
                //检查是否有文件输入框没有输入文件
                if(!file.isEmpty()) {
                    file.transferTo(new File("D:/temp/", file.getOriginalFilename()));
                }
            }
            
            return "/fileupload";
        }
        
        @RequestMapping("/download")
        public void download(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
            //得到当前上传缓存文件的位置
            String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            
            System.out.println(path);
            
            response.setCharacterEncoding("utf-8");
            
            response.setContentType("multipart/form-data");
            
            File file = new File(path + "/" + fileName);
            
            InputStream in = new FileInputStream(file);
            
            OutputStream out = response.getOutputStream();
            
            byte[] buff = new byte[1024];
            
            int length = 0;
            
            while((length = in.read(buff)) != -1) {
                out.write(buff);
            }
                    
            
        }
        
        
    }

    upload.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <form action="upload/file" method="post" enctype="multipart/form-data">
          
            file: <input type="file" name="file"><br>
            
            <input type="submit" value="submit">
        </form>
        
    <form action="upload/file2" method="post" enctype="multipart/form-data">
          
            file: <input type="file" name="file"><br>
            
            <input type="submit" value="submit">
        </form>
        
        <form action="upload/file3" method="post" enctype="multipart/form-data">
          
            file: <input type="file" name="file"><br>
            file: <input type="file" name="file"><br>
            
            <input type="submit" value="submit">
        </form>
    </body>
    </html>

    download.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <a href="upload/download?fileName=C语言游戏.doc">下载</a>
    </body>
    </html>

    spring.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:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:p="http://www.springframework.org/schema/p"  
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
        <context:component-scan base-package="youth.hong.annotation"></context:component-scan>
      

       <!-- 推荐使用这个标签定义注解的方式 -->
        <!-- <mvc:annotation-driven></mvc:annotation-driven> -->
        
      <!-- 使用bean注入的方式配置注解解析,现在不推荐了,仅作了解使用 --> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
      <!-- 古老的xml配置方式,使用这些bean定义你访问的url是想要调用哪个方法,仅作了解,现在没人还用这个 --> <!-- <bean name="/youth/hong" class="youth.hong.HelloWorld"></bean> <bean name="/multiple" class="youth.hong.MultiController"> <property name="methodNameResolver"> <ref bean="paraMethodResolver"/> </property> </bean> <bean name="/img" class="youth.hong.StaticController"> <property name="methodNameResolver"> <ref bean="paraMethodResolver"/> </property> </bean> <bean id="paraMethodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"> <property name="paramName"> 传参时的参数名http://localhost:8888/springMVC_003_multiple/multiple?action=update <value>action</value> </property> <property name="defaultMethodName"> <value>img</value> </property> </bean> --> <!-- 告知静态文件不要拦截,直接访问 --> <mvc:resources location="/image/" mapping="/dog/image/**"></mvc:resources> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 --> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop> </props> </property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" /> </beans>

    struts2框架上传下载

    Action.java

    package youth.hong;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.UUID;
    
    import org.apache.struts2.ServletActionContext;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    @SuppressWarnings("serial")
    public class Action extends ActionSupport{
        private String title;
        private File[] upload;//private List<File> upload
        private String[] uploadContentType;//private List<String>
        private String[] uploadFileName;
        private String savePath;
        private String allowTypes;
        
        public String getAllowTypes() {
            return allowTypes;
        }
        public void setAllowTypes(String allowTypes) {
            this.allowTypes = allowTypes;
        }
        
        public File[] getUpload() {
            return upload;
        }
        public void setUpload(File[] upload) {
            this.upload = upload;
        }
        public String[] getUploadContentType() {
            return uploadContentType;
        }
        public void setUploadContentType(String[] uploadContentType) {
            this.uploadContentType = uploadContentType;
        }
        public String[] getUploadFileName() {
            return uploadFileName;
        }
        public void setUploadFileName(String[] uploadFileName) {
            this.uploadFileName = uploadFileName;
        }
        public String getSavePath() {
            return savePath;
        }
        public void setSavePath(String savePath) {
            this.savePath = savePath;
        }
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        @Override
        public String execute() throws Exception {
            String[] types = this.getTypes();
            String check = this.fileFilter(types);
            System.out.println(check);
            if(check == null) {
                return INPUT;
            }
            String newName = null;
            FileInputStream fis = null;
            FileOutputStream fos = null;
            for(int i = 0; i < upload.length; i++) {
                
                newName = UUID.randomUUID() + uploadFileName[i].substring(uploadFileName[i].lastIndexOf('.'));
                uploadFileName[i] = newName;
                String path = ServletActionContext.getServletContext().getRealPath(savePath);
                System.out.println(path + "\" + newName);
                System.out.println(upload[i].getName());
                fis = new FileInputStream(upload[i]);
                fos = new FileOutputStream(path + "\" + newName);
                byte[] buff = new byte[1024];
                int len = 0;
                while((len=fis.read(buff)) > 0) {
                    fos.write(buff, 0, len);
                }
            }
            this.setUploadFileName(uploadFileName);
            fis.close();
            fos.close();
            return SUCCESS;
        }
        /**
         * 还可以使用struts2自带的fileUpload拦截器来过滤
         * @param types
         * @return
         */
        
        public String fileFilter(String[] types) {
            boolean check;
            for(int i = 0; i < upload.length; i++) {
                
                check = false;
                
                for(String string : types) {
                    if(uploadContentType[i].equals(string)) {
                        check = true;
                    }
                }
                
                if(!check) {
                    return null;
                }
            }
            return "continue";
        }
        
        public String[] getTypes() {
            String[] types = allowTypes.split(",");
            return types;
        }
        
    }

    struts.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    
    <struts>
    
        <!-- 动态地调用方法打开 -->
        <constant name="struts.enable.DynamicMethodInvocation" value="true" />
        <constant name="struts.devMode" value="true" />
        <constant name="struts.i18n.encoding" value="utf-8"></constant>
        <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
        <constant name="struts.custom.i18n.resources" value="global"></constant>
        
       
     
         <package name="youth" namespace="/" extends="struts-default">
         
             
             <action name="test" class="youth.hong.Action">
                 <interceptor-ref name="defaultStack"></interceptor-ref>
                 <interceptor-ref name="fileUpload">
              <!-- 使用拦截器进行文件上传操作的限制 --> <param name="allowedTypes">image/jpeg,image/jpg,image/bmp,image/png</param> <param name="maxSize">200000000000000</param><!-- 单位字节 --> </interceptor-ref> <param name="savePath">/upload</param>
            <!-- 手工进行文件上传的限制 --> <param name="allowTypes">image/jpeg,image/jpg,image/bmp,image/png</param> <result name="success">/success.jsp</result> <result name="input">/test.jsp</result> </action> </package> <!-- Add packages here --> </struts>

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
      <display-name>Struts2_001</display-name>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      </filter>
      <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping> 
    </web-app>

    upload.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="/struts-tags" prefix="s" %>
    <%=application.getRealPath("/upload") %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    /* function checkusername() {
        var username = document.getElementById("username");
        var request = new XMLHttpRequest();
        url = "path/index";
        request.open("POST", url, true);
        request.send(username.value);
    } */
    </script>
    </head>
    <body>
    <s:fielderror></s:fielderror>
    <s:head/>
    <form method="post" action="test" enctype="multipart/form-data">
        <input type="file" name="upload" /><br>
        <br>
        <input type="file" name="upload" /><br>
        <br>
        <input type="file" name="upload" /><br>
        <br>
        <input type="text" name="title" /><br>
        <br>
        <input type="submit" value="submit" />
    
    </form>
    
    </body>
    </html>

    success.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="/struts-tags" prefix="s"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <img src="/upload/<s:property value='uploadFileName'  />"/>
    
    </body>
    </html>

    Download

    package youth.hong;
    
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    
    import org.apache.struts2.ServletActionContext;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    @SuppressWarnings("serial")
    public class Action extends ActionSupport{
        private String inputName;
        private String contentType;
        private String fileName;
        
        public String getInputName() {
            return inputName;
        }
        public void setInputName(String inputName)  {
            this.getInputStream();
            System.out.println(inputName);
            try {
                inputName = new String(inputName.getBytes("ISO-8859-1"),"utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            this.inputName = inputName;
        }
        public String getContentType() {
            return contentType;
        }
        public void setContentType(String contentType)  {
            try {
                contentType = new String(contentType.getBytes("ISO-8859-1"),"utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            this.contentType = contentType;
        }
        public String getFileName() {
            return fileName;
        }
        public void setFileName(String fileName)  {
            try {
                fileName = new String(fileName.getBytes("ISO-8859-1"),"utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            this.fileName = fileName;
        }
        
        public InputStream getInputStream() {
            InputStream is = ServletActionContext.getServletContext().getResourceAsStream("/upload/warArea.jsp");
            System.out.println(is);
            return is;
        }
        
    }

    struts.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    
    <struts>
    
        <!-- 动态地调用方法打开 -->
        <constant name="struts.enable.DynamicMethodInvocation" value="true" />
        <constant name="struts.devMode" value="true" />
        <constant name="struts.i18n.encoding" value="utf-8"></constant>
        <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
        <constant name="struts.custom.i18n.resources" value="global"></constant>
        
       
     
         <package name="youth" namespace="/" extends="struts-default">
         
             
             <action name="download" class="youth.hong.Action">
                 <result name="success" type="stream">
                     <param name="contentType">${contentType}</param>
                     <param name="inputName">${getInputStream}</param>
                     <param name="contentDisposition">filename="${fileName}"</param>
                     <param name="bufferSize">800000000000000</param>
                 </result>
             </action>
       
        </package>
        
        
        <!-- Add packages here -->
    
    </struts>

    jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="/struts-tags" prefix="s" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    /* function checkusername() {
        var username = document.getElementById("username");
        var request = new XMLHttpRequest();
        url = "path/index";
        request.open("POST", url, true);
        request.send(username.value);
    } */
    </script>
    </head>
    <body>
    <a href="download?inputName=/upload/warArea.jpg&contentType=image/jpg&fileName=warArea.jpg">download</a>
    
    </body>
    </html>
  • 相关阅读:
    02_Python基础
    python 学习网站
    Docker搭建MySQL服务
    Ubuntu源、Python虚拟环境及pip源配置
    Ubuntu18.04完全卸载mysql5.7并安装mysql8.0的安装方法
    MySQL 数据库
    数据库连接池
    ssm整合开发的相关步骤和增删改查
    Springmvc执行流程
    资源映射之----在springmvc中如何访问WEB-INF目录下的文件和系统文件夹中的文件
  • 原文地址:https://www.cnblogs.com/honger/p/5846810.html
Copyright © 2011-2022 走看看