spring中文件上传与下载

一、文件上传

背景:该文件上传功能是在spring框架中实现的,事先应做的准备:

(1)导入文件上传所需的jar包,commons-fileupload、commons-io

(2)在配置文件中applicationContext.xml添加如下内容

  
           
          
          
   		

1.控制器中的代码:

@RequestMapping("/upload")
	public String uploadFile(HttpServletRequest request,@RequestParam("excelFile")MultipartFile file){
		//获取上传文件的名称
		String filePath = file.getOriginalFilename();
		File file2 = new File("file");
		if (!file2.exists()) {
			//创建临时目录
			file2.mkdir();
		}
		try {
			//文件存放的路径
			FileOutputStream fileOutputStream = new FileOutputStream(file2+"/"+filePath);
			fileOutputStream.write(file.getBytes());
			fileOutputStream.flush();
			fileOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "error";
		} catch (IOException e) {
			e.printStackTrace();
			return "error";
		}
	
		return UPLOADFILESUCC_PAGE;	
	}


2.jsp中的代码:


二、文件下载

控制器中代码:

@RequestMapping("/download")
	 public void downloadFile(String fileName,HttpServletResponse response){  
        response.setCharacterEncoding("utf-8");  
        response.setContentType("multipart/form-data");  
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);  
        try {  
            File file=new File(fileName);  
            System.out.println(file.getAbsolutePath());  
            InputStream inputStream=new FileInputStream("file/"+file);  
            System.out.println("11111111111"+file);
            OutputStream os=response.getOutputStream();  
            byte[] b=new byte[1024];  
            int length;  
            while((length=inputStream.read(b))>0){  
                os.write(b,0,length);  
            }  
            inputStream.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
	
jsp中代码:

注:该下载方式是输入文件名称下载,包括后缀名



你可能感兴趣的:(jsp,spring)