springmvc简单上传文件

本文详细介绍如何在SpringMVC框架下配置文件上传,包括设置文件大小限制、编码格式,以及实现文件上传到本地磁盘的过程。同时,分享了如何处理上传的文件,并返回特定JSON格式响应以适配layui富文本编辑器的图片上传需求。

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

1,配置springmvc.xml

    <!-- 文件上传配置 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 上传文件大小限制,上限为10MB,单位为字节 -->
        <property name="maxUploadSize">
            <value>10485760</value>
        </property>
        <!-- 请求编码格式,必须和JSP的pageEncoding属性一致,以便正确读取表单内容,默认为ISO-8859-1 -->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

2,页面

Request Method:POST,Request URL:http://localhost:8082/upload.do


3,后端

主要根据@RequestParam("file") MultipartFile file,获取页面传来的file

@RequestMapping("/upload")
	@ResponseBody
	public String upload(@RequestParam("file") MultipartFile file) throws Exception {
		String realPath="E:/temp_test/";
		 //获取文件名称 
	    String fileName = file.getOriginalFilename(); 
	    realPath=realPath + fileName;
	    
	    //写入本地磁盘 
	    InputStream is = file.getInputStream(); 
	    byte[] bs = new byte[1024]; 
	    int len; 
	    OutputStream os = new FileOutputStream(new File(realPath)); 
	    while ((len = is.read(bs)) != -1) { 
	      os.write(bs, 0, len); 
	    } 
	    os.close(); 
	    is.close(); 

		JSONObject json=new JSONObject();
		JSONObject jdata=new JSONObject();
		json.put("code",0);
		json.put("msg","成功");
		
		jdata.put("src",realPath);
		jdata.put("title",fileName);
		
		json.put("data",jdata);
		return json.toString();
	}

我上面返回的组装json格式主要是:我测试时用layui中富文本中的图片上传要返回固定格式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值