MultipartFile(文件的上传)--CommonsMul
2017-12-07 本文已影响843人
游园拾忆
SpringMVC 中,文件的上传,是通过 MultipartResolver 实现的。 所以,如果要实现文件的上传,只要在 spring-mvc.xml 中注册相应的 MultipartResolver 即可。
Spring_mvc.xml配置
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>
CommonsMultipartResolver 上传用到的两个包:
commons-fileupload:commons-fileupload:1.3.1
commons-io:commons-io:2.4
前端Jsp
<form action="${basepath}/uploadFileAction/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="file" name="file" />
<input type="submit" value="Submit" />
</form>
后台服务端
package net.jsshop.web.action;
import java.io.File;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.alibaba.fastjson.JSONObject;
@Controller
@RequestMapping(value = "/uploadFileAction")
public class uploadFileAction {
@RequestMapping(value = "/upload.do")
public void upload2(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("开始上传");
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> fileList = multiRequest.getFiles("file");
String sb = "";
for (MultipartFile mf : fileList) {
if (!mf.isEmpty()) {
// 取得当前上传文件的名称
String myFileName = mf.getOriginalFilename();
// 如果名称不为"",说明该文件存在,否则说明文件不存在。
if (myFileName.trim() != "") {
System.out.println(myFileName);
// 重命名上传后的文件
String filename = "demoupload-" + mf.getOriginalFilename();
// 定义上传路劲
String path = "E:/" + filename;
File localFile = new File(path);
mf.transferTo(localFile);
sb = sb + path + ",";
}
}
}
if (!"".equals(sb)) {
sb = sb.substring(0, sb.length() - 1);
JSONObject obj = new JSONObject();
obj.put("state", "ok");
obj.put("message", sb);
response.getWriter().print(obj.toString());
} else {
JSONObject obj = new JSONObject();
obj.put("state", "error");
obj.put("message", "没有上传文件");
response.getWriter().write(obj.toJSONString());
}
}
}
其他示例(转载的)
http://blog.csdn.net/programmer_sir/article/details/29570935