- 在applicationContext.xml中配置文件上传解决器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
- 编写jsp页面
<body>
<form action="uploadfile.htm" method="post" enctype="multipart/form-data">
<input type="file" name="file" value=""/><br/>
<input type="submit" value="上传"/>
</form>
</body>
- 在controller中执行代码
package com.zbrx.trace.action_bs
import java.io.File
import java.io.IOException
import javax.servlet.http.HttpServletRequest
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Controller
import org.springframework.util.FileCopyUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.MultipartHttpServletRequest
import com.zbrx.trace.base.action.ProjBaseAction
@Controller
@Scope("prototype")
public class UpLoadController extends ProjBaseAction {
@RequestMapping("/uploadfile")
public void upload(HttpServletRequest request) {
MultipartHttpServletRequest req = (MultipartHttpServletRequest)request
MultipartFile file = req.getFile("file")
if (!file.isEmpty()) {
String filename = file.getOriginalFilename()
System.out.println(filename)
try {
//绝对路径
String tomcatPath = request.getServletContext().getRealPath("/img//")
FileCopyUtils.copy(file.getBytes(), new File(tomcatPath +"/" + filename))
} catch (IOException e) {
e.printStackTrace()
}
}
}
}