文件上传之 MultipartFile
利用MultipartFile(组件)实现文件上传
在java中上传文件似乎总有点麻烦,没.net那么简单,记得最开始的时候用smartUpload实现文件上传,最近在工作中使用spring的MultipartFile实现文件上传,感觉挺简单,在这里和大家分享一下.
一.主要有两个java类,和一般的servlet放在一起即可.
1.FileUploadBean.java
package chb.demo.web;
import org.springframework.web.multipart.MultipartFile;
public class FileUploadBean {
private MultipartFile file;
public void setFile(MultipartFile file) {
this.file = file;
}
public MultipartFile getFile() {
return file;
}
}
2.FileUploadController.java
package chb.demo.web;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class FileUploadController extends SimpleFormController {
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors){
try
{
// cast the bean
FileUploadBean bean = (FileUploadBean) command;
// let's see if there's content there
MultipartFile file = bean.getFile();
if (file == null) {
throw new Exception("上传失败:文件为�空");
}
if(file.getSize()>10000000)
{
throw new Exception("上传失败:文件大小不能超过10M");
}
//得到文件�名
String filename=file.getOriginalFilename();
if(file.getSize()>0){
try {
SaveFileFromInputStream(file.getInputStream(),"D:/",filename);
} catch (IOException e) {
System.out.println(e.getMessage());
return null;
}
}
else{
throw new Exception("上传失败:上传文件不能为�空");
}
// well, let's do nothing with the bean for now and return:
try {
return super.onSubmit(request, response, command, errors);
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
return null;
}
}
public void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException
{
FileOutputStream fs=new FileOutputStream( path + "/"+ filename);
byte[] buffer =new byte[1024*1024];
int bytesum = 0;
int byteread = 0;
while ((byteread=stream.read(buffer))!=-1)
{
bytesum+=byteread;
fs.write(buffer,0,byteread);
fs.flush();
}
fs.close();
stream.close();
}
}
二.配置文件中如下配置:
1.web.xml,利用spring mvc模式,大家应该都很熟悉了
<servlet>
<servlet-name>chb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>chb</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
2.chb-servlet.xml,这里要配置映射,并可以设定最大可上传文件的大小
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- Multi-Action 用来标识method的变量名定义-->
<bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName">
<value>action</value>
</property>
<property name="defaultMethodName">
<value>index</value>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="10000000"/>
</bean>
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/upload.do">fileUploadController</prop>
</props>
</property>
</bean>
<bean id="fileUploadController" class="chb.demo.web.FileUploadController">
<property name="commandClass" value="chb.demo.web.FileUploadBean"/>
<!-- 上传失败时跳转页面 -->
<property name="formView" value="/user/err.jsp"/>
<!-- 上传成功时跳转页面 -->
<property name="successView" value="/user/confirmation.jsp"/>
</bean>
</beans>
三.设定jsp页面
<form id="form1" method="post" action="upload.do" enctype="multipart/form-data">
<tr>
<td width="25%" align="right">上传文件:</td>
<td><input id="file" type="file" NAME="file" style="width:300px;"></td>
</tr>
<tr align="center" valign="middle">
<td height="60" colspan="2"><input type="submit" ID="BtnOK" value="确认上传"></td>
</tr>
</form>
ok,现在就可以上传文件了,挺简单吧?这里我只列出了基本步骤,至于具体的操作(比如中文问题)可能就需要大家自己再完善完善了.
原文博客地址:http://blog.csdn.net/hbcui1984/article/details/1498112
文件上传之 MultipartFile的更多相关文章
- 文件上传之MultipartFile使用
转载 文件断点上传,html5实现前端,java实现服务器 一.单/多文件上传使用例子: 工程路径如下 -src |--main.java --controller --service ...
- 文件上传api——MultipartFile
MultipartFile 方法总结 byte[] getBytes() 返回文件的内容作为一个字节数组. String getContentType() 返回文件的内容类型. InputStr ...
- MultipartFile 多文件上传的应用
公司的项目很多地方要用到文件上传,以前的上传主要是用apache的fileupload ,使用的感受并不太好.今天试了试spring的MultipartFile,感觉还不错,封装的比较简洁. 当然,中 ...
- springmvc图片文件上传接口
springmvc图片文件上传 用MultipartFile文件方式传输 Controller package com.controller; import java.awt.image.Buffer ...
- SpringMVC文件上传下载
在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/q ...
- Spring MVC 文件上传 & 文件下载
索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: pom.xml WebConfig.java index.jsp upload.jsp FileUploadCon ...
- Springboot文件上传代码笔记
1.在src下创建filter包,包内Class名UploadFilter package com.gd.filter; import org.apache.catalina.servlet4prev ...
- javaweb简单的实现文件上传
java代码: // @RequestMapping(value = "/upload.do", method = RequestMethod.POST) @RequestMapp ...
- SpringMVC国际化与文件上传
点击阅读上一章 其实SpringMVC中的页面国际化与上一章的验证国际化基本一致. 1.对页面进行国际化 1)首先我们对Spring配置文件中添加国际化bean配置 <!-- 注册国际化信息,必 ...
随机推荐
- JavaScript基础入门教程(一)
本系列教程的说明 本教程说白了可以说是我自己学习JavaScript的笔记,主要内容参考自<JavaScript权威指南>,部分内容可能来自互联网,本系列教程假设学者之前学过c或者其它的编 ...
- 使用nsswitch控制linux dns解析顺序
参考:1.DNS原理入门参考:http://www.ruanyifeng.com/blog/2016/06/dns.html 2.http://cn.linux.vbird.org/linux_ser ...
- 二十四种设计模式:观察者模式(Observer Pattern)
观察者模式(Observer Pattern) 介绍定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动刷新. 示例有一个Message实体类,某些对象 ...
- iOS:极光推送控制器跳转
在前面已经做完了极光消息的推送,那么有消息了,如何跳转到需要的控制器呢?其实,主要还是在userInfo这个消息里面做判断来处理,具体如下: 下面这两个是远程推送时接收消息的方法,这是应用程序提供的方 ...
- spring的条件装配bean
1 应用程序环境的迁移 问题: 开发软件时,有一个很大的挑战,就是将应用程序从一个环境迁移到另一个环境. 例如,开发环境中很多方式的处理并不适合生产环境,迁移后需要修改,这个过程可能会莫名的出现很多b ...
- MySQL建表设置外键提示错误
错误内容: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to ...
- VP9 Video Codec
http://www.webmproject.org/vp9/ WebM Repositories libvpx: VP8/VP9 Codec SDK pull http://git.chromi ...
- [Angular] Improve Server Communication in Ngrx Effects with NX Data Persistence in Angular
Communicating with a remote server via HTTP presents an extra level of complexity as there is an inc ...
- 关于configure和Makefile
http://blog.csdn.net/lltaoyy/article/details/7615833 转篇文章,讲的不是很清楚,再附上几个资料连接,来自http://www.linuxdw.com ...
- 【树莓派】【转载】Raspberry Pi (树莓派)折腾记
在网上看到一篇对树莓派折腾记录比较详细的文章,时间比较早,但是有些东西没变. 对于新手而言,还是有点参考价值.文章参见:http://skypegnu1.blog.51cto.com/8991766/ ...
package chb.demo.web;

public void setFile(MultipartFile file) {
}
}