文件上传与下载

2021-07-31 17:56

阅读:721

标签:real   sts   mvc   rac   数据   byte   body   url   ase   文件上传和下载 一、创建SpringMVC项目 略 二、导入支持的包 commons-fileupload commons-fileupload 1.4 javax.servlet javax.servlet-api 4.0.1 provided 三、配置applicationContext.xml 四、前端 $Title$ 五、controller层 @RestController public class FileController { @RequestMapping("/upload") public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { String uploadFileName = file.getOriginalFilename(); //文件名为空返回首页 if ("".equals(uploadFileName)){ return "redirect:/index.jsp"; } System.out.println("上传文件名:"+uploadFileName); //上传路径保存设置 String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } System.out.println("上传文件保存地址:"+realPath); InputStream is = file.getInputStream(); FileOutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //读取写出 int len=0; byte[] buffer = new byte[1024]; while ((len=is.read(buffer))!=-1){ os.write(buffer,0,len); os.flush(); } os.close(); is.close(); return "redirect:/index.jsp"; } //采用file.Transto来保存上传的文件 @RequestMapping("/upload2") public String upload2(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException { //上传路径保存设置 String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //上传文件地址 System.out.println("上传文件保存地址:"+realPath); //通过CommonsMultipartFile的方法直接写文件 file.transferTo(new File(realPath+"/"+file.getOriginalFilename())); return "redirect:/index.jsp"; } } @RequestMapping(value = "/download") public String downloads(HttpServletResponse response,HttpServletRequest request)throws Exception{ //要下载图片的地址 String path = request.getServletContext().getRealPath("/upload"); String fileName="1.png"; //1、设置response响应头 response.reset();//清空缓存 response.setCharacterEncoding("UTF-8"); response.setContentType("multipart/form-data");//二进制传输数据 //设置响应头 response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8")); File file = new File(path, fileName); //2、读取文件 FileInputStream is = new FileInputStream(file); //3、写出文件 OutputStream out = response.getOutputStream(); int index=0; byte[] buffer = new byte[1024]; while ((index=is.read(buffer))!=-1){ out.write(buffer,0,index); out.flush(); } out.close(); is.close(); return null; } 文件上传与下载标签:real   sts   mvc   rac   数据   byte   body   url   ase   原文地址:https://www.cnblogs.com/rongchengbanxia/p/14924384.html

上一篇:win10定时执行php脚本

下一篇:4、HTTP


评论


亲,登录后才可以留言!