spring中的文件上传实际比较容易
1、页面中
<html>
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="uploadfile" />
<input type="submit" value="提交" />
</form>
</body>
</html>
2、修改spring的配置文件添加
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>1048576</value>
</property>
</bean>
其中class部分可以选用CommonsMutipartResolver或CosMultipartResolver,但是别忘记添加相应的jar文件
3、对应的控制器和实体类中无需添加uploadfile文件
4、对应的Controller
package cn.com.babe;
import java.io.DataOutputStream;
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.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class UploadAction extends SimpleFormController {
private String viewsucc;
private String viewfalse;
public String getViewsucc() {
return viewsucc;
}
public void setViewsucc(String viewsucc) {
this.viewsucc = viewsucc;
}
public String getViewfalse() {
return viewfalse;
}
public void setViewfalse(String viewfalse) {
this.viewfalse = viewfalse;
}
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
String view = getViewfalse();
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile orginalFile = (CommonsMultipartFile) multipartRequest
.getFile("uploadfile");// 表单中对应的文件名;
if (orginalFile != null && !orginalFile.isEmpty()) {// 如果有文章中带有附件
String filename = orginalFile.getOriginalFilename();
DataOutputStream out = new DataOutputStream(new FileOutputStream(
"c:/" + filename));// 存放文件的绝对路径
InputStream is = null;// 附件输入流
try {
is = orginalFile.getInputStream();
byte[] b=new byte[is.available()];
is.read(b);
out.write(b);
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (is != null) {
is.close();
}
if (out != null) {
out.close();
}
}
view=getViewsucc();
}
return new ModelAndView(view, null);
}
}
通过上面的方式就可以文件上传了。我做的只是把所有的上传文件拷贝到c盘根目录下,并且设置了上传文件最大大小为1mb。
http://red-apple.blog.163.com/blog/static/201165061201211661026753/