批量上传文件到服务器
利用MultipartFormDataInput实现。
简单说明:MultipartFormDataInput会读取multipart/form-data类型数据过来的head和body,且以特定符号分割里面的内容,
利用测试工具fiddler 测试上传接口就会发现 选择需要上传的文档时候会以一定格式分割。
比如我们上传两个文件到服务器上
实现代码:
Java代码
- @POST
- @Path ("/upload")
- @Consumes("multipart/form-data")
- @Produces("text/plain; charset=utf-8")
- public synchronized String manyFileUpload(MultipartFormDataInput input) throws Exception {
- logger.info("开始上传多个文件---------");
- //获取head和body所有数据,返回一个list,上传单个文件的时候 直接get0 get1即可得到文件名和上传的内容
- logger.debug("读取文件头1:{}",input.getParts());
- // logger.debug("读取文件头2:{}",input.getFormData());
- //获取获取head和body所有数据,返回一个map,可通过key来获取指定的head或body内容
- logger.debug("读取文件头3:{}",input.getFormDataMap());
- logger.debug("读取文件头4:{}",input.getPreamble());
- Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
- List<InputPart> bodys = uploadForm.get("Filedata");//得到上传文件的内容
- List<InputPart> heads = uploadForm.get("fileName");//得到上传文件的名称,主要获取后缀
- //定义上传服务器的路径
- String webPath = "D:/ccc/cc/cc-ws/src/main/webapp/upload";
- String fileNames = null;
- //获取上传文件头和内容的总数,除以2就是要生成文件的个数(因为上传文件都是文件名和文件内容成对出现,如果多个附件一个文件名,传两遍文件名,
- 上传服务器的保存的时候加上年月日时分秒,分辨附件,方便对应下载)
- for(int i=0;i<input.getParts().size()/2;i++){
- InputPart body = bodys.get(i);
- InputPart head = heads.get(i);
- //读取头,获取文件名
- InputStream is = head.getBody(InputStream.class,
- null);
- //读取一遍名字
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- int j = -1;
- while ((j = is.read()) != -1) {
- baos.write(j);
- }
- //中文名字转码,根据需要转格式,也许是utf-8
- String fileName = baos.toString("GBK");
- //得到上传文件保存的路径
- String realFile = webPath + File.separator + fileName;
- //读取内容,写入文件输出
- InputStream inputStream = body.getBody(InputStream.class,
- null);
- File file = new File(realFile);
- FileUtils.copyInputStreamToFile(inputStream, file);
- logger.info("上传保存文件成功 返回生成的文件名: {} , 真实路径 : {}", fileName,
- realFile);
- if(fileNames == null)
- fileNames = fileName;
- else
- fileNames = fileNames+"||"+fileName;
- }
- //根据具体需求返回结果
- return fileNames;
- }
测试代码:
采用html测试,即上图
Java代码
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'fileupload.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">
- </head>
- <body>
- <!-- enctype 默认是 application/x-www-form-urlencoded action 对应接口地址 input标签中的name对应文件名与内容-->
- <form action="http://localhost:8080/cc/excel/upload"
- enctype="multipart/form-data" method="post">
- <h4>批量上传 </h4>
- 注:文件名为上传附件的名字 <br/>
- 文件名:<input type="text" name="fileName"> 附件:<input type="file" name="Filedata"><br/>
- 文件名:<input type="text" name="fileName"> 附件:<input type="file" name="Filedata"><br/>
- <input type="submit" value="提交"/>
- </form>
- </body>
- </html>