Upload and download files

To upload files, we need to select and import two related jar packages

commons-fileupload-1.3.3.jar
    
    commons-io-2.5.jar

Hand over org.springframework.web.multipart.commons.CommonsMultipartResolver to Spring's IOC container for management. The configuration id="multipartResolve" IOC container will initialize itself when it is opened.

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <!-- 设置默认字符集为UTF-8 -->
      <property name="defaultEncoding" value="UTF-8"/>
      <!-- 设置下载的文件最大上传限制 -->
      <property name="maxUploadSize" value="4666666"/>
      </bean>

The following is the implementation code

@Controller
    @RequestMapping("/upload")
    public class UpLoadController {
     // 只是做一个跳转
    	@RequestMapping("/toup")
    	public String toup(){
    		
    		return "upload/upload";
    		
    	}
    	//只是将文件传到自己的电脑上
    	@RequestMapping("/upload")
    	public String upLoad(MultipartFile ooo) throws IllegalStateException, IOException{
    	
    		long size = ooo.getSize();
    		System.out.println(size);
    		String filename = ooo.getOriginalFilename();
    		File file = new File("D:/upload/file");
    		if(!file.exists()){
    			file.mkdirs();
    		}
    		ooo.transferTo(new File(file,filename));	
    		return "upload/index";
    	}
    	
    	//将文件上传上页面上去的 附带页面
    	@RequestMapping("/uploa")
    	public String uploa(MultipartFile ooo, HttpServletRequest req) throws IllegalStateException, IOException{
    		//获取文件的真实名称
    		String filename = ooo.getOriginalFilename();
    		//获取文件的大小
    		ooo.getSize();
    		//获取项目的路径并创建指定文件夹
    		String path = req.getServletContext().getRealPath("/upload");
    		System.out.println("path:"+path);
    		//将字符串的文件地址转换成文件格式
    		File savePath = new File(path);
    		//判断文件是否存在 不存在就给他创建一个
    		if(!savePath.exists()){
    			savePath.mkdirs();
    		}
    		//将上传的真实名称的文件放到我们创建的文件夹内
    		ooo.transferTo(new File(savePath,filename));
    		//获取文件的相对路径保存到Request内 在页面提取就容易了 页面提取图片的Src只支持相对路径
    		req.setAttribute("path", req.getContextPath()+"/upload/"+filename);
    		System.out.println(req.getAttribute("path"));
    		return "upload/index";
    	}
    	
    }

page code here

<body>
    上传成功<img alt="8888" src="${path }">
    </body>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326353218&siteId=291194637