springboot里表单里单个文件上传

该博客详细介绍了如何在SpringBoot应用中实现单个文件的上传。通过使用MultipartFile接口和HttpServletRequest,将上传的文件保存到服务器指定路径,并返回文件的URL。在控制器类中定义了上传方法,处理文件并进行异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

​ springboot里表单里单个文件上传

  • 表单里单个文件上传类似于现实中,给朋友发送qq邮件等类似情景

    @Controller
    public class UpLoadController {
     //创建格式化日期对象
    	SimpleDateFormat sdf=new SimpleDateFormat();
    	@RequestMapping("/index1")
    	public String index(){
    		return "index";
    	}
    	
    	@RequestMapping("/upload")
    	@ResponseBody
    	public String upload(MultipartFile file,HttpServletRequest request){
    	//MultipartFile是spring提供的一个接口,用来接收multipart/form-data类型
    		String format=sdf.format(new Date());
    		String path=request.getServletContext().getRealPath("/file");
    		//创建一个路径下文件夹对象
    		File folder=new File(path);
    		判断文件是否真正存在,如果不存在,创建一个
    		if(!folder.exists()){
    			//mkdir()只能创建单层目录文件夹
    			//mkdirs()能创建多层目录文件夹
    			folder.mkdirs();
    		}
    		
    	
    		String oldName=file.getOriginalFilename();
    		String newName=UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
    		try {
    			file.transferTo(new File(folder,newName));
    			//request.getSchema()可以返回当前页面使用的协议,http 或是 https
    			String url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/img"+format+newName;
    		    System.out.println(url);
    		    return "success";
    		}catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		return "error";
    		
    	}
    	
    

    此代码是controller层的,整体能运行成功,如有注释或者别的方面错了可以留言

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值