文件上传下载及上传预览
js文件 实现当上传图片的时候可以预览图片
$(function () { $("input[type=file]").change(function(){ // 获取FileList的第一个元素 var t = $(this)[0].files[0]; /* t.name;//获取图片名字 t.size//图片大小 t.type;//类型*/ var src = window.URL.createObjectURL(t); $(this).next().attr("src",src); }); });
HTML文件
<input type="file" name="imgFile" accept="image/*"/> <img width="160px" height="120px"/></br> <input type="file" name="imgFile" accept="image/*"/> <img width="160px" height="120px"/></br> <input type="file" name="imgFile" accept="image/*"/> <img width="160px" height="120px"/></br>
文件上传 先导入jar包
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
//单文件上传 @RequestMapping("/upload") public String up(@RequestParam("imgFile")MultipartFile imgFile) throws IOException ,IllegalStateException { String filePath = "F://upload/"; String fileName = imgFile.getOriginalFilename(); imgFile.transferTo(new File(filePath+fileName)); return "/index.jsp"; } //多文件上传 @RequestMapping("/uploads") public String ups(HttpServletRequest request) throws IOException ,IllegalStateException{ //获取上传的文件集合 List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("imgFile"); //设定绝对路径 String filePath = "F://upload/"; System.out.println(files.size()); //遍历上传文件 for(MultipartFile file:files){ //判断文件是否为空 if(!file.isEmpty()){ //调用transferTo(new File())方法上传文件 file.transferTo(new File(filePath+file.getOriginalFilename())); } } return "/index.jsp"; }
文件下载
@RequestMapping("/download") protected void download(HttpServletResponse response) throws Exception { //选择下载文件 String filePath = "F://upload/2.jpg"; File file = new File(filePath); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1); //文件路径有中文,会无法识别文件格式, //URLEncoder.encode();转换字符串格式 fileName = URLEncoder.encode(fileName, "UTF-8"); response.reset(); //文件响应MIME类型, //不知道类型application/octet-stream response.setContentType("application/octet-stream"); //激活文件下载对话框 response.addHeader("Content-Disposition", "attachment;filename="+fileName); /*String len = String.valueOf(file.length()); //指定文件长度 response.setHeader("Content-Length", len);*/ //IO流读写文件,将文件下载 OutputStream os = response.getOutputStream(); FileInputStream is = new FileInputStream(file); byte[] b = new byte[1024]; int n; while((n=is.read(b))!=-1){ os.write(b, 0, n); } is.close(); os.close(); System.out.println("下载完成"); }
上一篇:
IDEA上Java项目控制台中文乱码