天天看点

java批量上传文件_java文件批量上传、zip方式批量下载

1 packagecom.achong.controller;2

3 importjava.io.BufferedInputStream;4 importjava.io.BufferedOutputStream;5 importjava.io.File;6 importjava.io.FileInputStream;7 importjava.io.FileOutputStream;8 importjava.io.IOException;9 importjava.io.InputStream;10 importjava.io.OutputStream;11 importjava.util.ArrayList;12 importjava.util.List;13 importjava.util.UUID;14

15 importjavax.servlet.ServletContext;16 importjavax.servlet.ServletException;17 importjavax.servlet.http.HttpServletRequest;18 importjavax.servlet.http.HttpServletResponse;19 importjavax.servlet.http.HttpSession;20

21 importorg.apache.tools.zip.ZipEntry;22 importorg.apache.tools.zip.ZipOutputStream;23 importorg.springframework.http.HttpHeaders;24 importorg.springframework.http.HttpStatus;25 importorg.springframework.http.ResponseEntity;26 importorg.springframework.stereotype.Controller;27 importorg.springframework.web.bind.annotation.RequestMapping;28 importorg.springframework.web.bind.annotation.RequestParam;29 importorg.springframework.web.multipart.MultipartFile;30

31 @Controller32 public classHelloHandler {33

34 @RequestMapping("/hello")35 publicString hello(){36 return "success";37 }38

39

53 @RequestMapping("/upload")54 public String upload(@RequestParam("fileName")String fileName,55 @RequestParam("photo")MultipartFile[] file){56 //保存

57 System.out.println("普通项的值:"+fileName);58 for(MultipartFile multipartFile : file) {59 if(multipartFile!=null&&!multipartFile.isEmpty()){60 File file2 = new File("C:/Users/Administrator/Desktop/上传下载测试/"+multipartFile.getOriginalFilename());61 try{62 multipartFile.transferTo(file2);63 } catch (IllegalStateException |IOException e) {64 //TODO Auto-generated catch block

65 e.printStackTrace();66 }67 }68 }69 return "success";70 }71

72 @RequestMapping("/singleDownload")73 public ResponseEntity downloadImg(HttpSession session) throwsIOException{74 //=============造响应体=============75 //1、创建一个ResponseEntity对象。这个对象里面既有响应头还有响应体;

76 ServletContext servletContext =session.getServletContext();77 //1、获取到图片的流,直接交给浏览器;ServletContext.可以从当前项目下获取资源78 //2、获取到图片的流

79 InputStream is = servletContext.getResourceAsStream("/Desert.jpg");80 //创建一个和流一样多的数组

81 byte[] body = new byte[is.available()];82 //3、将流的数据放在数组里面

83 is.read(body);84 is.close();85

86 //==============造响应头================

87 HttpHeaders headers = newHttpHeaders();88 //文件下载的响应头89 //按照以前乱码的解决方式;90

91 //文件名乱码解决

92 String filename="单个图片.jpg";93 filename = new String(filename.getBytes("GBK"),"ISO8859-1");94 headers.add("Content-Disposition", "attachment; filename="+filename);95 //第一个参数代表给浏览器的响应数据(响应体)96 //第二个参数代表当前响应的响应头(定制响应头)MultiValueMap97 //第三个参数代表当前响应状态码(statusCode)HttpStatus

98 ResponseEntity re = new ResponseEntity(body, headers, HttpStatus.OK);99

100 returnre;101 }102

103

107 @RequestMapping("/multDownloadZip")108 public voiddownloadFiles(HttpServletRequest request, HttpServletResponse response)109 throwsServletException, IOException {110 //获取页面上需要批量下载的链接

111 List files = new ArrayList();112 String outFilePath = request.getSession().getServletContext().getRealPath("/")113 + "upload";114 System.out.println(outFilePath);115 File Allfile = newFile(outFilePath);116 System.out.println("Allfile: " +Allfile.getPath());117 if(Allfile.exists()) {118 //得到项目跟路径upload下所有的文件和目录的绝对路径

119 File[] fileArr =Allfile.listFiles();120 for(File file2 : fileArr) {121 files.add(file2);122 }123 }124

125 String fileName = UUID.randomUUID().toString() + ".zip";126 //在服务器端创建打包下载的临时文件

127 System.out.println("outFilePath: " +outFilePath);128 createFile(outFilePath, fileName);129 File file = new File(outFilePath + "\\" +fileName);130 //文件输出流

131 FileOutputStream outStream = newFileOutputStream(file);132

136 ZipOutputStream toClient = newZipOutputStream(outStream);137 toClient.setEncoding("gbk");138 zipFile(files, toClient);139 toClient.close();140 outStream.close();141 this.downloadFile(file, response, true);142 }143

144 //创建文件

145 public voidcreateFile(String path, String fileName) {146 //path表示你所创建文件的路径, fileName为文件名

147 File file = newFile(path, fileName);148 System.out.println(file.getPath());149 if (!file.exists()) {150 try{151 file.createNewFile();152 } catch(IOException e) {153 e.printStackTrace();154 }155 }156

157 }158

159

166 public static void zipFile(List files, ZipOutputStream outputStream) throwsIOException, ServletException {167 try{168 int size =files.size();169 //压缩列表中的文件

170 for (int i = 0; i < size; i++) {171 File file =(File) files.get(i);172 zipFile(file, outputStream);173 }174 } catch(IOException e) {175 throwe;176 }177 }178

179

186 public static void zipFile(File inputFile, ZipOutputStream outputstream) throwsIOException, ServletException {187 try{188 if(inputFile.exists()) {189 if(inputFile.isFile()) {190 FileInputStream inStream = newFileInputStream(inputFile);191 BufferedInputStream bInStream = newBufferedInputStream(inStream);192

195 ZipEntry entry = newZipEntry(inputFile.getName());196 outputstream.putNextEntry(entry);197

198 final int MAX_BYTE = 10 * 1024 * 1024; //最大的流为10M

199 long streamTotal = 0; //接受流的容量

200 int streamNum = 0; //流需要分开的数量

201 int leaveByte = 0; //文件剩下的字符数

202 byte[] inOutbyte; //byte数组接受文件的数据

203

204 streamTotal = bInStream.available(); //通过available方法取得流的最大字符数

205 streamNum = (int) Math.floor(streamTotal / MAX_BYTE); //取得流文件需要分开的数量

206 leaveByte = (int) streamTotal % MAX_BYTE; //分开文件之后,剩余的数量

207

208 if (streamNum > 0) {209 for (int j = 0; j < streamNum; ++j) {210 inOutbyte = new byte[MAX_BYTE];211 //读入流,保存在byte数组

212 bInStream.read(inOutbyte, 0, MAX_BYTE);213 outputstream.write(inOutbyte, 0, MAX_BYTE); //写出流

214 }215 }216 //写出剩下的流数据

217 inOutbyte = new byte[leaveByte];218 bInStream.read(inOutbyte, 0, leaveByte);219 outputstream.write(inOutbyte);220 outputstream.closeEntry(); //Closes the current ZIP entry221 //and positions the stream for222 //writing the next entry

223 bInStream.close(); //关闭

224 inStream.close();225 }226 } else{227 throw new ServletException("文件不存在!");228 }229 } catch(IOException e) {230 throwe;231 }232 }233

234

240 public void downloadFile(File file, HttpServletResponse response, booleanisDelete) {241 try{242 //以流的形式下载文件。

243 BufferedInputStream fis = new BufferedInputStream(newFileInputStream(file.getPath()));244 byte[] buffer = new byte[fis.available()];245 fis.read(buffer);246 fis.close();247 //清空response

248 response.reset();249 OutputStream toClient = newBufferedOutputStream(response.getOutputStream());250 response.setContentType("application/octet-stream");251 response.setHeader("Content-Disposition",252 "attachment;filename=" + new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));253 toClient.write(buffer);254 toClient.flush();255 toClient.close();256 if(isDelete) {257 file.delete(); //是否将生成的服务器端文件删除

258 }259 } catch(IOException ex) {260 ex.printStackTrace();261 }262 }263 }