精华内容
下载资源
问答
  • Java多文件上传

    2012-02-23 13:24:37
    Java多文件上传
  • java 多文件上传

    2015-01-16 09:09:17
    java 多文件上传代码 在spring 配置文件中如何配置
  • Java 多文件上传

    2008-05-05 14:43:46
    Java 多文件上传
  • java多文件上传

    热门讨论 2013-08-01 10:42:46
    里面实现了 java多文件上传 自动上传和选择完毕后一起上传 利用struts 上传 直接用 dopost上传 通过FileUtils类上传的 和 io 上传的 里面都有,很详细。
  • java多文件上传实现

    2013-12-19 09:44:46
    java多文件上传实现,上传界面采用flash,同时显示上传进度条
  • java 多文件上传插件

    2021-05-26 10:29:25
    java后台管理时用的多文件上传插件,java1.8环境前皆可用
  • java 多文件上传下载

    2011-08-05 09:59:50
    java多文件上传 如果要动态的 可以修改 上传页面
  • axios+java多文件上传

    2021-05-31 09:30:21
    axios+java多文件上传 本文均为简单示例代码,仅为 多文件 上传提供思路,和前端传参、后端接收参数,并非完整上传demo 如果误导了大家,请见谅 前端 html <el-button type="primary" @click="startSelectFile...

    本文均为简单示例代码,仅为 多文件 上传提供思路,和前端传参、后端接收参数,并非完整上传demo

    如果误导了大家,请见谅

    前端

    html

    <el-button type="primary" @click="startSelectFile">点我开始上传</el-button>
    <!-- 隐藏的上传 input                                                                              -->
    <input type="file" multiple="multiple" size="200" v-show="false" ref="uploadFileInputRef" @change="selectedFile">
    

    js

    // 点击按钮开始选择文件
    startSelectFile(){
        this.$refs.uploadFileInputRef.click();
    },
    // input文件域的 change事件
    selectedFile(e) {
      this.uploadFile("/test/upload", e.target.files).then((res) => {
        console.log(res);
      });
    },
    // 使用 axions 封装一个多文件上传方法(正常来说,这个应该会封装在一个全局的js中,供所有页面使用,此处为方便理解,直接写在页面的 methods 中)
    uploadList (path, data) {
        var formData = new FormData();
        if (data && data.length) {
            data.forEach(item => {
                formData.append("files", item)
            })
            return new Promise(function (resolve) {
                axios
                    .post(path, formData, {
                        headers: {
                            'Content-Type': "multipart/form-data",
                        }
                    })
                    .then(function (response) {
                        resolve(response.data);
                    })
            });
        }
    }
    

    java后端

    @PostMapping("/upload")
    public String upload(@RequestParam("files") MultipartFile[] files){
        for(MultipartFile file : files){
            System.out.println(file.getOriginalFilename());
        }
        return "上传成功";
    }
    
    展开全文
  • java多文件上传plupload控件实现多图片上传(一) 续写PluploadUtil 和 Plupload PO类,以及后台的action。 至此,可实现多文件上传功能。 上传文件Action类: import gwm.xtkf.rights.domain.User...

    接上篇

    java多文件上传plupload控件实现多图片上传(一)

    续写PluploadUtil 和 Plupload PO类,以及后台的action。

    至此,可实现多文件上传功能。

     

    上传文件Action类:

    import gwm.xtkf.rights.domain.UserSession;  
    import gwm.xtkf.tool.AliyunOSSUtil;  
    import gwm.xtkf.tool.ResourceUtil;  
    import gwm.xtkf.tool.ResultMessage;  
    import gwm.zls.filemanage.util.Plupload;  
    import gwm.zls.filemanage.util.PluploadUtil;  
      
    import java.io.IOException;  
    import java.util.Date;  
    import java.util.List;  
    import java.util.UUID;  
      
    import javax.servlet.http.HttpServletRequest;  
    import javax.servlet.http.HttpServletResponse;  
    import javax.servlet.http.HttpSession;  
      
    import org.springframework.beans.factory.annotation.Autowired;  
    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 xs.jszx.housemanage.domain.HousePic;  
    import xs.jszx.housemanage.service.HousePicService;  
      
      
    @Controller  
    @RequestMapping("/housePicController")  
    public class HousePicController {  
          
        @Autowired  
        private HousePicService housePicService;  
        //多文件上传  
        @RequestMapping("/saveHousePics"  )    
        public String saveHousePics(HousePic housePic,Plupload plupload,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IllegalStateException, IOException {    
              
            UserSession userSession = (UserSession)session.getAttribute("userSession");  
              
            plupload.setRequest(request);    
                //文件存储路径    
            String fileName = plupload.getName();  
            String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());  
            String realName = UUID.randomUUID().toString() + suffix;  
              
            try {    
                 PluploadUtil.upload2AliyunOSS(plupload, realName);    
                //判断文件是否上传成功(被分成块的文件是否全部上传完成)    
                if (PluploadUtil.isUploadFinish(plupload)) {  
                    housePic.setRealName(realName);  
                    housePic.setUserId(userSession.getUserId());   
                    housePic.setCreateTime(new Date());  
                    //写入数据库  
                    if (this.housePicService.saveHousePic(housePic)){  
                        return "housemanage/pic_inc/pic_houseMain";  
                    }  
                }    
                    
            } catch (IllegalStateException e) {  
                // TODO Auto-generated catch block    
                e.printStackTrace();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block    
                e.printStackTrace();    
            }  
              
            return "housemanage/pic_inc/pic_houseMain";  
        }  
          

     

    PluploadUtil 类:

    import gwm.xtkf.tool.AliyunOSSUtil;  
    import gwm.xtkf.tool.ResourceUtil;  
    import java.io.BufferedOutputStream;  
    import java.io.File;  
    import java.io.FileOutputStream;  
    import java.io.IOException;  
    import java.io.InputStream;  
    import java.io.OutputStream;  
    import java.util.Iterator;  
    import java.util.List;  
      
    import org.springframework.util.MultiValueMap;  
    import org.springframework.web.multipart.MultipartFile;  
    import org.springframework.web.multipart.MultipartHttpServletRequest;  
      
      
      
    public class PluploadUtil {    
        private static final int BUF_SIZE = 2 * 1024;  
        /**上传失败响应的成功状态码*/    
        public static final String RESP_SUCCESS = "{\"jsonrpc\" : \"2.0\", \"result\" : \"success\", \"id\" : \"id\"}";    
        /**上传失败响应的失败状态码*/    
        public static final String RESP_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}";    
            
            
        /**  
         * 用于Plupload插件的文件上传  到阿里OSS  
         * @param plupload - 存放上传所需参数的bean  
         * @param filename - 保存的文件名  
         * @throws IllegalStateException  
         * @throws IOException  
         */    
        public static void upload2AliyunOSS(Plupload plupload, String filename) throws IllegalStateException, IOException {    
            int chunks = plupload.getChunks();  //获取总的碎片数    
            int chunk = plupload.getChunk();    //获取当前碎片(从0开始计数)    
                
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) plupload.getRequest();     
            MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();    
                
            if(map != null) {    
                //事实上迭代器中只存在一个值,所以只需要返回一个值即可    
                Iterator<String> iter = map.keySet().iterator();    
                while(iter.hasNext()) {    
                    String str = (String) iter.next();    
                    List<MultipartFile> fileList =  map.get(str);    
                    for(MultipartFile multipartFile : fileList) {    
                        //因为只存在一个值,所以最后返回的既是第一个也是最后一个值    
                        plupload.setMultipartFile(multipartFile);    
                        //存储到oss上文件路径和名称  
                        String key = ResourceUtil.getOSSHousesPic() + filename;  
                          
                        AliyunOSSUtil.ensureBucket();  
                        //当chunks>1则说明当前传的文件为一块碎片,需要合并    
                        if (chunks > 1) {    
                              
                            String prefix = filename.substring(0, filename.lastIndexOf(".")-1);  
                            String suffix = filename.substring(filename.lastIndexOf("."), filename.length());  
                            File tmpFile = File.createTempFile(prefix, suffix);  
                            //需要创建临时文件名,最后再更改名称    
                            //如果chunk==0,则代表第一块碎片,不需要合并    
                            saveUploadFile(multipartFile.getInputStream(), tmpFile, chunk == 0 ? false : true);    
                                
                            //上传并合并完成,则将临时名称更改为指定名称    
                            if (chunks - chunk == 1) {    
                                AliyunOSSUtil.uploadFile(key, tmpFile);  
                            }    
                        } else {    
                            AliyunOSSUtil.uploadMultipartFile(key, multipartFile);  
                            //否则直接将文件内容拷贝至新文件    
                            //multipartFile.transferTo(targetFile);    
                        }    
                    }    
                }    
            }    
                
        }    
            
          
        /**  
         * 用于Plupload插件的文件上传  上传到本地服务器 
         * @param plupload - 存放上传所需参数的bean  
         * @param dir - 保存目标文件目录  
         * @throws IllegalStateException  
         * @throws IOException  
         */         
        public static void upload2Local(Plupload plupload, String filePath, String fileName) throws IllegalStateException, IOException {    
                              
            int chunks = plupload.getChunks();  //获取总的碎片数    
            int chunk = plupload.getChunk();    //获取当前碎片(从0开始计数)    
                
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) plupload.getRequest();     
            MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();    
                
            if(map != null) {    
                File dir = new File(filePath);  
                  
                if (!dir.exists()) dir.mkdirs();    //如果目标文件夹不存在则创建新的文件夹    
                    
                //事实上迭代器中只存在一个值,所以只需要返回一个值即可    
                Iterator<String> iter = map.keySet().iterator();    
                while(iter.hasNext()) {    
                    String str = (String) iter.next();    
                    List<MultipartFile> fileList =  map.get(str);    
                    for(MultipartFile multipartFile : fileList) {    
                        //因为只存在一个值,所以最后返回的既是第一个也是最后一个值    
                        plupload.setMultipartFile(multipartFile);    
                            
                        //创建新目标文件    
                        File targetFile = new File(dir.getPath()+ "/" + fileName);    
                        //当chunks>1则说明当前传的文件为一块碎片,需要合并    
                        if (chunks > 1) {    
                            //需要创建临时文件名,最后再更改名称    
                            File tempFile = new File(dir.getPath()+ "/" + multipartFile.getName());    
                            //如果chunk==0,则代表第一块碎片,不需要合并    
                            saveUploadFile(multipartFile.getInputStream(), tempFile, chunk == 0 ? false : true);    
                                
                            //上传并合并完成,则将临时名称更改为指定名称    
                            if (chunks - chunk == 1) {    
                                tempFile.renameTo(targetFile);    
                            }    
                                
                        } else {    
                            //否则直接将文件内容拷贝至新文件    
                            multipartFile.transferTo(targetFile);    
                        }    
                    }    
                }    
            }    
                
        }  
          
          
        /**  
         * 保存上传文件,兼合并功能  
         */    
        private static void saveUploadFile(InputStream input, File targetFile, boolean append) throws IOException {    
            OutputStream out = null;    
            try {    
                if (targetFile.exists() && append) {    
                    out = new BufferedOutputStream(new FileOutputStream(targetFile, true), BUF_SIZE);    
                } else {    
                    out = new BufferedOutputStream(new FileOutputStream(targetFile), BUF_SIZE);    
                }    
                    
                byte[] buffer = new byte[BUF_SIZE];    
                int len = 0;    
                //写入文件    
                while ((len = input.read(buffer)) > 0) {    
                    out.write(buffer, 0, len);    
                }    
            } catch (IOException e) {    
                throw e;    
            } finally {    
                //关闭输入输出流    
                if (null != input) {    
                    try {    
                        input.close();    
                    } catch (IOException e) {    
                        e.printStackTrace();    
                    }    
                }    
                if (null != out) {    
                    try {    
                        out.close();    
                    } catch (IOException e) {    
                        e.printStackTrace();    
                    }    
                }    
            }    
        }    
            
        /**  
         * 判断是否全部上传完成  
         * 碎片需合并后才返回真  
         */    
        public static boolean isUploadFinish(Plupload plupload) {    
            return (plupload.getChunks() - plupload.getChunk() == 1);    
        }    
            
    }    

     

    Plupload PO类:

    import javax.servlet.http.HttpServletRequest;  
    import org.springframework.web.multipart.MultipartFile;  
      
    /**  
     * Plupload是一个上传插件。  
     * 这是一个bean类,主要存储Plupload插件上传时需要的参数。  
     * 属性名不可随意改动.  
     * 这里主要使用MultipartFile文件上传方法  
     */    
    public class Plupload {    
            
        /**文件临时名(打文件被分解时)或原名*/    
        private String name;    
        /**总的块数*/    
        private int chunks = -1;    
        /**当前块数(从0开始计数)*/    
        private int chunk = -1;    
        /**HttpServletRequest对象,不能直接传入进来,需要手动传入*/    
        private HttpServletRequest request;    
        /**保存文件上传信息,不能直接传入进来,需要手动传入*/    
        private MultipartFile multipartFile;    
            
        public String getName() {    
            return name;    
        }    
        
        public void setName(String name) {    
            this.name = name;    
        }    
        
        public int getChunks() {    
            return chunks;    
        }    
        
        public void setChunks(int chunks) {    
            this.chunks = chunks;    
        }    
        
        public int getChunk() {    
            return chunk;    
        }    
        
        public void setChunk(int chunk) {    
            this.chunk = chunk;    
        }    
        
        public HttpServletRequest getRequest() {    
            return request;    
        }    
        
        public void setRequest(HttpServletRequest request) {    
            this.request = request;    
        }    
        
        public MultipartFile getMultipartFile() {    
            return multipartFile;    
        }    
        
        public void setMultipartFile(MultipartFile multipartFile) {    
            this.multipartFile = multipartFile;    
        }    
            
    }    

     

    转载于:https://my.oschina.net/u/2451795/blog/1057835

    展开全文
  • java多文件上传(有例子).zip java多文件上传(有例子).zip
  • java多文件上传

    2016-03-09 17:15:42
    文件上传: 上传"> </form>
  • Flex+Java多文件上传

    2019-05-26 01:02:57
    NULL 博文链接:https://zmfkplj.iteye.com/blog/486241
  • Java多文件上传下载

    2018-10-11 22:22:21
    先上图,这是一个用MyEclipse写的文件上传和下载。 下图是上传的界面,点击按钮可以选择文件。(页面比较丑,勿喷) 下图是上传多个文件,点击“单击此处添加更多文件”,则会出现多个按钮,选择多个文件,不...

     先上图,这是一个用MyEclipse写的文件上传和下载。


    下图是上传的界面,点击按钮可以选择文件。(页面比较丑,勿喷)

    下图是上传多个文件,点击“单击此处添加更多文件”,则会出现多个按钮,选择多个文件,不需要时移除即可。

    点击提交后,就会跳转到下图,下载列表,会显示上传的文件。

    点击相应的文件名,即可下载。(下图左下角即为我下载的图片)


    下图是项目相关文件。


    接下来就是上代码了。

    第一个页面:upload1.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'Upload1.jsp' starting page</title>
        
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    
        <style type="text/css">
    		.button:nth-child(6n){
    				margin-right: 0;
    			}
    			.button.gray{
    				color: #8c96a0;
    				text-shadow:1px 1px 1px #fff;
    				border:1px solid #dce1e6;
    				box-shadow: 0 1px 2px #fff inset,0 -1px 0 #a8abae inset;
    				background: -webkit-linear-gradient(top,#f2f3f7,#e4e8ec);
    				background: -moz-linear-gradient(top,#f2f3f7,#e4e8ec);
    				background: linear-gradient(top,#f2f3f7,#e4e8ec);
    			}
    			.round,
    			    .side,
    			    .tags{
    						padding-right: 30px;
    					}
    			.round:after{
    				position: absolute;
    				display: inline-block;
    				content: "\003c";
    				top:50%;
    				right:10px;
    				margin-top: -10px;
    				width: 17px;
    				height: 20px;
    				padding-left: 3px;
    				line-height:18px;
    				font-size: 10px;
    				font-weight: normal;
    				border-radius: 10px;
    				text-shadow:-2px 0 1px #333;
    				-webkit-transform:rotate(-90deg);
    				-moz-transform:rotate(-90deg); 
    				transform:rotate(-90deg);
    			}
    			.gray.round:after{
    				box-shadow:1px 0 1px rgba(255,255,255,1) inset,1px 0 1px rgba(0,0,0,.2);
    				background:-webkit-linear-gradient(top,#dce1e6,#dde2e7);
    				background:-moz-linear-gradient(top,#dce1e6,#dde2e7);
    				background:linear-gradient(top,#dce1e6,#dde2e7);
    				text-shadow:-2px 0 1px #fff;
    			}
    			.side:after{
    				position: absolute;
    				display: inline-block;
    				content: "\00bb";
    				top:3px;
    				right:-4px;
    				width: 38px;
    				height:30px;
    				font-weight: normal;
    				line-height: 26px;
    				border-radius:0 0 5px 5px;
    				text-shadow:-2px 0 1px #333;
    				-webkit-transform:rotate(-90deg);
    				-moz-transform:rotate(-90deg);
    				transform:rotate(-90deg);
    			}
    			.gray.side:after{
    				text-shadow:-2px 0 1px #fff;
    				border-top: 1px solid #d4d4d4;
    				box-shadow:-2px 0 1px #eceef1 inset;
    				background:-webkit-linear-gradient(right,#e1e6ea,#f2f2f6 60%);
    				background:-moz-linear-gradient(right,#e1e6ea,#f2f2f6 60%);
    				background:linear-gradient(right,#e1e6ea,#f2f2f6 60%); 
    			}
    			.tags:after{
    				font-weight: normal;
    				position: absolute;
    				display: inline-block;
    				content: "FREE";
    				top:-3px;
    				right: -33px;
    				color: #fff;
    				text-shadow:none;
    				width: 85px;
    				height:25px;
    				line-height: 28px;
    				-webkit-transform:rotate(45deg) scale(.7,.7);
    				-moz-transform:rotate(45deg) scale(.7,.7);
    				transform:rotate(45deg) scale(.7,.7);
    			}
    			.gray.tags:after{
    				background: #8c96a0;
    				border:2px solid #fff;  
    			}
    			.button.rarrow,
    			    .button.larrow{
    								overflow:visible;
    							}
    			.rarrow:after,  
    			    .rarrow:before,
    			    .larrow:after,  
    			    .larrow:before{
    								position:absolute;
    								content: "";
    								display: block;
    								width: 28px;
    								height: 28px;
    								-webkit-transform:rotate(45deg);
    								-moz-transform:rotate(45deg);
    								transform:rotate(45deg);
    							}
    			.rarrow:before{
    				width: 27px;
    				height: 27px;
    				top: 6px;
    				right: -13px;
    				clip: rect(auto auto 26px 2px);
    			}
    			.rarrow:after{
    				top: 6px;
    				right: -12px;
    				clip: rect(auto auto 26px 2px);
    			}
    			.gray.rarrow:before{
    				background: #d6dbe0;
    			}
    			.gray.rarrow:after{
    				box-shadow: 0 1px 0 #fff inset,-1px 0 0 #b7babd inset;
    				background:-webkit-linear-gradient(top left,#f2f3f7,#e4e8ec);
    				background:-moz-linear-gradient(top left,#f2f3f7,#e4e8ec);
    				background:linear-gradient(top left,#f2f3f7,#e4e8ec);
    			}
    			.larrow:before{
    				top: 6px;
    				left: -13px;
    				width: 27px;
    				height: 27px;
    				clip: rect(2px 26px auto auto);
    			}
    			.larrow:after{
    				top: 6px;
    				left: -12px;
    				clip: rect(2px 26px auto auto);
    			}
    			.gray.larrow:before{
    				background: #d6dbe0;
    			}
    			.gray.larrow:after{
    				box-shadow: 0 -1px 0 #b7babd inset,1px 0 0 #fff inset;
    				background:-webkit-linear-gradient(top left,#f2f3f7,#e4e8ec);
    				background:-moz-linear-gradient(top left,#f2f3f7,#e4e8ec);
    				background:linear-gradient(top left,#f2f3f7,#e4e8ec);
    			}
    			.gray:hover{
    				background: -webkit-linear-gradient(top,#fefefe,#ebeced);
    				background: -moz-linear-gradient(top,#f2f3f7,#ebeced);
    				background: linear-gradient(top,#f2f3f7,#ebeced);
    			}
    			.gray:active{
    				top:1px;
    				box-shadow: 0 1px 3px #a8abae inset,0 3px 0 #fff;
    				background: -webkit-linear-gradient(top,#e4e8ec,#e4e8ec);
    				background: -moz-linear-gradient(top,#e4e8ec,#e4e8ec);
    				background: linear-gradient(top,#e4e8ec,#e4e8ec);
    			}
    			.gray.side:hover:after{
    				background:-webkit-linear-gradient(right,#e7ebee,#f8f8f8 60%);
    				background:-moz-linear-gradient(right,#e7ebee,#f8f8f8 60%);
    				background:linear-gradient(right,#e7ebee,#f8f8f8 60%);
    			}
    			.gray.side:active:after{
    				top:4px;
    				border-top: 1px solid #9fa6ab;
    				box-shadow:-1px 0 1px #a8abae inset;
    				background:-webkit-linear-gradient(right,#e4e8ec,#e4e8ec 60%);
    				background:-moz-linear-gradient(right,#e4e8ec,#e4e8ec 60%);
    				background:linear-gradient(right,#e4e8ec,#e4e8ec 60%); 
    			}
    			.black.rarrow:hover:after,
    			    .black.larrow:hover:after{
    					background:-webkit-linear-gradient(top left,#818181,#575757);
    					background:-moz-linear-gradient(top left,#818181,#575757);
    					background:linear-gradient(top left,#818181,#575757);
    				}
    			.gray.rarrow:active:after,
    			    .gray.larrow:active:after{
    					background:-webkit-linear-gradient(top left,#e4e8ec,#e4e8ec);
    					background:-moz-linear-gradient(top left,#e4e8ec,#e4e8ec);
    					background:linear-gradient(top left,#e4e8ec,#e4e8ec);
    				}
    			.gray.rarrow:active:after{
    				box-shadow: 0 1px 0 #b7babd inset,-1px 0 0 #b7babd inset;
    			}
    			.gray.larrow:active:after{
    				box-shadow: 0 -1px 0 #b7babd inset,1px 0 0 #b7babd inset;
    			}
    			html {
    			  height: 100%;
    			}
    		body {
    			  height: 100%;
    			  font: 1.33em 'Roboto Condensed', arial;
    			  color: #FFF;
    			  text-align: center;
    			  background-image: -webkit-radial-gradient(circle, #3c3b52 0%, #252233 80%);
    			  background-image: radial-gradient(circle, #3c3b52 0%, #252233 80%);
    			}
    		h1 {
    			  margin: .5em 0 0;
    			  margin-bottom:20px;
    			  padding: 0;
    			  text-shadow: 0 4px rgba(0, 0, 0, 0.2);
    			}
    		* {
    			  -moz-box-sizing: padding-box;
    			       box-sizing: padding-box;
    			}
    		input[type=file]{
    			border-color:#fff;
    			/* border: none; */
    			outline:none;
    			cursor: pointer;
    			height:45px;
    			text-align: center;
    		}
    		.button{
    				/* width: 240px; */
    				line-height: 38px;
    				text-align: center;
    				font-weight: bold;
    				color: #fff;
    				text-shadow:1px 1px 1px #333;
    				border-radius: 5px;
    				margin:0 20px 20px 0;
    				position: relative;
    				overflow: hidden;
    			}
        </style>
        <script type="text/javascript">
    	    function addline(){
    	        newline = document.all.test.insertRow();
    	        newline.insertCell().innerHTML="<input class='button gray side' type='file' name='file' size='60'>"+"<a onclick='javascript:removeline(this)'>移除</a>";  
    	    }
    	    
    	    function removeline(obj){
    	        var objSourceRow=obj.parentNode.parentNode;
    	        var objTable=obj.parentNode.parentNode.parentNode.parentNode; 
    	        objTable.lastChild.removeChild(objSourceRow);
    	    }
        </script>
    	</head>
       <body>
    	   <form name="theform" method="post" action="${pageContext.request.contextPath }/FileUpLoadServlet1" enctype="multipart/form-data">
    	       <h1 align="center">文件上传</h1>
    	       <table id=test border="0" align="center">
    	           <tr>
    	               <td>
    	                   <input class="button gray side" type="file" name="file" size="60">&nbsp;
    	                   <a onclick="addline()"><font color="white">单击此处添加更多文件</font></a>
    	               </td>
    	           </tr>
    	       </table>
    	       <hr>
    	       <input type="submit" style="width: 100;height: 40;font-size: 18px" />
    	   </form>
      </body>
    </html>
    

    第二个页面:ListFile.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'ListFile.jsp' starting page</title>
        
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	<style type="text/css">
    			a{
    				text-decoration: none;
    				color: rgba(255, 255, 255, 0.5);
    			}
    			.live {
    			  overflow: hidden;
    			}
    			.live > li {
    			  list-style: none;
    			  position: relative;
    			  padding: 0 0 0 2em;
    			  margin: 0 0 .5em 10px;
    			  -webkit-transition: .12s;
    			          transition: .12s;
    			}
    			.live > li>a::before {
    			  position: absolute;
    			  content: '\2022';
    			  font-family: Arial;
    			  color: #FFF;
    			  top: 0;
    			  left: 0;
    			  text-align: center;
    			  font-size: 2em;
    			  opacity: .5;
    			  line-height: .75;
    			  -webkit-transition: .5s;
    			          transition: .5s;
    			}
    			.live > li>a:hover {
    			  color: #FFF;
    			}
    			.live > li>a:hover::before {
    			  -webkit-transform: scale(2);
    			      -ms-transform: scale(2);
    			          transform: scale(2);
    			  opacity: 1;
    			  text-shadow: 0 0 4px;
    			  -webkit-transition: .1s;
    			          transition: .1s;
    			}
    			.live.type2 > li>a::before {
    			  content: '';
    			  width: 10px;
    			  height: 10px;
    			  background: #FFF;
    			  border-radius: 3px;
    			  line-height: 0;
    			  top: .27em;
    			  left: 5px;
    			}
    			.live.type2 > li>a:hover::before {
    			  -webkit-transform: none;
    			      -ms-transform: none;
    			          transform: none;
    			  border-radius: 5px;
    			  width: 25px;
    			  left: -10px;
    			  background: #BA5353;
    			}
    			html {
    			  height: 100%;
    			}
    			
    			body {
    			  height: 100%;
    			  font: 1.33em 'Roboto Condensed', arial;
    			  color: #FFF;
    			  text-align: center;
    			  background-image: -webkit-radial-gradient(circle, #3c3b52 0%, #252233 80%);
    			  background-image: radial-gradient(circle, #3c3b52 0%, #252233 80%);
    			}
    			
    			h1 {
    			  margin: .5em 0 0;
    			  padding: 0;
    			  text-shadow: 0 4px rgba(0, 0, 0, 0.2);
    			}
    			
    			* {
    			  -moz-box-sizing: padding-box;
    			       box-sizing: padding-box;
    			}
    			
    			ul {
    			  width: 28%;
    			  display: inline-block;
    			  text-align: left;
    			  vertical-align: top;
    			  background: rgba(0, 0, 0, 0.2);
    			  color: rgba(255, 255, 255, 0.5);
    			  border-radius: 5px;
    			  padding: 1.5em;
    			  margin: 2%;
    			  box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
    			}
    
    
    		</style>
    
      </head>
      
      <body>
      	<h1>下载列表</h1><br>
      	<ul class="live type2">
    	  	<c:if test="${not empty list }">
    	  		<c:forEach items="${list }" var="fileName">
    	  			<li><a href="${pageContext.request.contextPath }/DownServlet?fileName=${fileName}">${fn:substringAfter(fileName,"~~")}</a></li>
    	  		</c:forEach>
    	  	</c:if>
        </ul>
      </body>
    </html>
    

    filter包下面的字符过滤器:EncodingFilter

    package filter;
    
    import java.io.IOException;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class EncodingFilter implements Filter{
    
    	public void destroy() {
    		
    	}
    
    	public void doFilter(ServletRequest req, ServletResponse resp,
    			FilterChain chain) throws IOException, ServletException {
    		//代理模式
    		//转型
    		final HttpServletRequest request=(HttpServletRequest)req;
    		HttpServletResponse response=(HttpServletResponse)resp;
    		//处理公共业务
    		request.setCharacterEncoding("utf-8");
    		response.setContentType("text/html;charset=utf-8");
    		//对指定接口的某个方法进行功能扩展,使用代理,即对request对象创建代理对象
    		/*
    		 * public static Object newProxyInstance(ClassLoader loader,
                                              Class<?>[] interfaces,
                                              InvocationHandler h)
            */
    		HttpServletRequest proxy=(HttpServletRequest)Proxy.newProxyInstance(
    				request.getClass().getClassLoader(),//指定类加载器
    				new Class[]{HttpServletRequest.class},//接口类型 
    				new InvocationHandler() {//事件处理器
    					
    					public Object invoke(Object proxy, Method method, Object[] args)
    							throws Throwable {
    						//定义方法的返回值
    						Object returnValue=null;
    						String methodName=method.getName();
    						//判断:get方法
    						if("getParameter".equals(methodName)){
    							//调用目标对象的方法
    							String value=request.getParameter(args[0].toString());
    							String methodSubmit=request.getMethod();
    							if("get".equals(methodSubmit)){
    								if(value!=null && !"".equals(value.trim())){
    									//处理中文乱码
    									value=new String(value.getBytes("ISO8859-1"),"utf-8");
    								}
    							}
    							return value;
    						}else{
    							//执行request对象的其他方法
    							returnValue=method.invoke(request, args);
    						}
    						return returnValue;
    					}
    				});
    		//放行
    		chain.doFilter(proxy, response);
    		
    	}
    
    	public void init(FilterConfig arg0) throws ServletException {
    
    	}
    
    }
    

    在 web.xml配置

    <filter>
      	<filter-name>EncodingFilter</filter-name>
      	<filter-class>filter.EncodingFilter</filter-class>
      </filter>
      <filter-mapping>
      	<filter-name>EncodingFilter</filter-name>
      	<url-pattern>/*</url-pattern>
      </filter-mapping>

    上传的servlet:FileUpLoadServlet1

    package upload;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
    import java.util.UUID;
    
    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.FileItemFactory;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    public class FileUpLoadServlet1 extends HttpServlet {
    
    	
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		FileItemFactory factory=new DiskFileItemFactory();
    		ServletFileUpload upload=new ServletFileUpload();
    		upload.setFileItemFactory(factory);
    		upload.setFileSizeMax(1024*1024*30);//单个文件不超过30m
    		upload.setSizeMax(1024*1024*100);//总文件不超过100m
    		upload.setHeaderEncoding("utf-8");//设置编码,防止乱码
    		if(upload.isMultipartContent(request)){
    			try {
    				List<FileItem> list=upload.parseRequest(request);
    				for (FileItem fileItem : list) {
    					if(!fileItem.isFormField()){
    						String name=fileItem.getName();
    						if(name!=null && !"".equals(name)){
    							String uuid=UUID.randomUUID().toString();
    							String path=getServletContext().getRealPath("/upload");
    							name=uuid+"~~"+name;
    							File file=new File(path,name);
    							fileItem.write(file);
    							response.getWriter().write("单个文件上传成功!");
    						}
    						
    					}
    				}
    				response.getWriter().write("多个文件上传成功!");
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}else{
    			response.getWriter().write("不处理!");
    		}
    		response.sendRedirect(request.getContextPath()+"/ListFileServlet");
    	}
    
    	
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    		doGet(request, response);
    	}
    
    }
    

    显示下载列表的servlet:ListFileServlet

    package upload;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ListFileServlet extends HttpServlet {
    
    	
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    		List<String> list=new ArrayList<String>();
    		String path=getServletContext().getRealPath("/upload");
    		File file=new File(path);
    		if(file.isDirectory()){
    			File[] files=file.listFiles();
    			for (File file2 : files) {
    				String fileName=file2.getName();
    				list.add(fileName);
    			}
    		}
    		request.setAttribute("list", list);
    		request.getRequestDispatcher("/ListFile.jsp").forward(request, response);
    	}
    
    	
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    		doGet(request, response);
    	}
    
    }
    

    下载的servlet:DownServlet

    package upload;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.io.IOUtils;
    
    public class DownServlet extends HttpServlet {
    
    	
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String fileName=request.getParameter("fileName");
    		String path=getServletContext().getRealPath("/upload");
    		File file=new File(path,fileName);
    		if(!file.exists()){
    			response.getWriter().print("该文件不存在!");
    			return;
    		}
    		response.addHeader("content-disposition", "attachment;filename="+fileName);
    		IOUtils.copy(new FileInputStream(file), response.getOutputStream());
    		
    	}
    
    	
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    		
    	}
    
    }
    

    所有代码已上传,上传后的文件会放在tomcat服务器里面,所以在自己的项目下是找不到文件的,必须去tomcat的webapps目录下,找到自己的项目名,然后再找到upload,就可以看见上传的文件了。

    项目所需jar包地址:https://download.csdn.net/download/rosachampagne/10717258

     

     

     

     

     


    展开全文
  • jsp/java多文件上传DEMO

    2014-09-04 09:26:59
    一次选择多个文件,多文件上传,uploadify,完整DEMO
  • NULL 博文链接:https://af8991.iteye.com/blog/2144774
  • 多文件上传
    public ResultJson fileUpload(HttpServletRequest request,
                HttpServletResponse response) {
            // TODO Auto-generated method stub
            ResultJson resultJson = new ResultJson();
            CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
            /**
             * 检查form中是否有enctype="multipart/form-data"
             */
            if (multipartResolver.isMultipart(request)) {
                /**
                 * 将request变成多部分request
                 */
                MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
                /**
                 * 获取multiRequest 中所有的文件名
                 */
                Iterator iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    MultipartFile file=multiRequest.getFile(iter.next().toString());
                    if (file!=null) {
                        /**
                         * 保存在resource/appImages路径下
                         */
                        String path = request.getSession().getServletContext().getRealPath("/") + "/resource/appImages/";
                        /**
                         * 1.String realPath = request.getSession().getServletContext().getRealPath("/resource/appImages/") ;
                         * 2.String realPath = request.getSession().getServletContext().getRealPath("/") + "/resource/appImages/";
                         * 1和2的写法得到的结果是不一样的,前者不能进入appImages路径,只能到resource
                         */
                        File fileItem = new File(path);
                        if (!fileItem.exists()) {
                            fileItem.mkdir();
                        }
                        String realName = path + file.getOriginalFilename();
                        try {
                            /**
                             * 上传文件到指定位置
                             */
                            file.transferTo(new File(realName));
                            resultJson.setState(true);
                            imgUrl.append("resource/appImages/"+file.getOriginalFilename()+",");
                            /**
                             * flag = 0表示上传成功,1表示失败,2表示没有文件上传。为投诉新增接口判断做铺垫
                             */
                            resultJson.setFlag("0");
                            resultJson.setMessage(imgUrl.toString());
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            resultJson.setState(false);
                            /**
                             * 上传失败
                             */
                            resultJson.setFlag("1");
                            e.printStackTrace();
                        } 
                    }
                }
            } else {
                resultJson.setState(false);
                /**
                 * 没有文件可上传
                 */
                resultJson.setFlag("2");
            }
            return resultJson;
        }
    展开全文
  • java语言开发,使用springMVC+Hibernate+Spring,框架,多文件上传,代码可以直接运行,涉及的数据库自动创建

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 5,286
精华内容 2,114
关键字:

java多文件上传

java 订阅