Spring3文件上传,提速你的Web开发
?? ??? ??? value="1000000"/>
?????? </bean>
清单2:
web.xml
在web.xml文件中添加以下代码:
?? <servlet>??
????? <servlet-name>springmvc</servlet-name>??
????? <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>??
????? <load-on-startup>2</load-on-startup>??
?? </servlet>??
?<servlet-mapping>??
???? <servlet-name>springmvc</servlet-name>??
???? <url-pattern>/</url-pattern>??
?</servlet-mapping>??
清单3
upload.html
建立一个普通的html文件,加入以下代码:
<form method="post" action="/SpringREST/image/imageUpload" enctype="multipart/form-data">
??? <input type="file" name="file" />
??? <input type="submit"? value="upload"/>
</form>
清单4
ImageController.java
package com.javabloger.springrest.action;
import java.io.FileOutputStream;
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.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.javabloger.springrest.dao.ImageDAO;
@Controller
@RequestMapping("/image")??
public class ImageController {
??? @RequestMapping("/imageUpload")??
??? public String processImageUpload(
??? ??? ??? ??? @RequestParam() MultipartFile file??? // 关键就是这句话起了作用
??? ??? ??? ??? ) throws Exception {
??? ??? ??? if (!file.isEmpty()) {
??? ??? ??? ??? byte[] bytes = file.getBytes();
??? ??? ??? ??? FileOutputStream fos = new FileOutputStream("d:/upload/"+file.getOriginalFilename()); // 上传到写死的上传路径
??? ??? ??? ??? fos.write(bytes);? //写入文件
??? ??? ??? ? }
??? ??? ??? System.out.println ("name: "+file.getOriginalFilename()+"? size: "+file.getSize() );? // 打印文件大小和文件名称
??? ??? ??? ?return "redirect:/image";?? // 跳转你所指定的页面名称
??? ??? ??? }
}
通过上一篇文章“Spring3 REST MVC框架,提速你的Web开发 ”在结合本篇文章的代码,我相信你也能很快的感受到Spring3的魅力。让我再熟悉一段时间,我会去看看Spring3中的源代码,我非常的好奇、非常的有兴趣。
?–end–