【Maven+SSM】补充:写一个文件上传的请求

来源:互联网 发布:算法工程师的年薪 编辑:程序博客网 时间:2024/06/08 09:40

补充:写一个文件上传的请求

基于上篇文章的项目,项目地址:

一、添加Jar包:


二、配置springmvc文件上传:springmvc-servlet.xml

<!-- 上传文件 resolveLazily延时加载,推迟文件解析,捕获异常--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxUploadSize" value="209715200"></property><property name="defaultEncoding" value="UTF-8"></property><property name="resolveLazily" value="true"></property></bean>
三、写一个Controller:

package controller;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;@Controllerpublic class FileUpLoadController {private static Logger log = LoggerFactory.getLogger(RequestController.class);@RequestMapping(value="/upload",method=RequestMethod.GET)public String fileUpload() {return "upload";}@RequestMapping(value="/doUpload",method=RequestMethod.POST)public String doUpload(@RequestParam("file")MultipartFile file) {if (!file.isEmpty()) {log.debug("文件拷贝中------",file.getOriginalFilename());}return "successupload";}}
upload.jsp如下:其中enctype为multipart/form-data。其中action<%=request.getContextPath()%>/doUpload

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><form method="post" action="<%=request.getContextPath()%>/doUpload" enctype="multipart/form-data"><input type="file" name="file"><input type="submit"></form></body></html>
其中上传/doUpload的controller修改存在本地的某个位置。

@RequestMapping(value="/doUpload",method=RequestMethod.POST)public String doUpload(@RequestParam("file")MultipartFile file) throws IOException {if (!file.isEmpty()) {log.debug("文件拷贝中------",file.getOriginalFilename());FileUtils.copyInputStreamToFile(file.getInputStream(),new File("/Users/user/eclipse-workspace/mvnStudy01/src/main/resources/uploadimg",System.currentTimeMillis()+file.getOriginalFilename()));}return "successupload";}
四、上传测试:

查看发现路径下图片上传成功。








原创粉丝点击