spring文件上传

首先需要两个jar文件

commons-io-2.5.jar

commons-fileupload-1.3.1.jar

当然版本根据自己需要选择

设置文件上传配置,在spring配置文件,加入文件上传配置

 <!--文件上传  -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>  
</bean>


html文件

<form action="/fileController/upload.action" method="post" enctype="multipart/form-data">  

<input type="file" name="file" /> <input type="submit" value="Submit" /></form>




package com.neutron.admin.controller;


import java.io.File;
import java.io.IOException;


import javax.servlet.http.HttpServletRequest;


import org.eclipse.jetty.http.HttpField;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import com.neutron.admin.model.dto.Json;




/**文件上传处理**/
@Controller
@RequestMapping("/fileController")
public class FileController {


@RequestMapping("/upload")
@ResponseBody
public Json upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) throws IllegalStateException, IOException{
Json json=new Json();

//文件上传路径
String path= request.getSession().getServletContext().getRealPath("/upload");  
String fileName=file.getOriginalFilename();
File tfile=new File(path,fileName);


if(!tfile.exists()){//没有路径,自动创建   这里路径在项目文件夹下
tfile.mkdirs();


}

file.transferTo(tfile);
json.setMsg(request.getContextPath()+"/upload/"+fileName);
return json;
}


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值