Spring mvc 文件上传到文件夹(转载+心得)

时间:2023-03-09 01:00:01
Spring mvc 文件上传到文件夹(转载+心得)

spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方
1.form的enctype=”multipart/form-data” 这个是上传文件必须的
2.applicationContext.xml中 <bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”/> 关于文件上传的配置不能少

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
  7. default-lazy-init="true">
  8. <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
  9. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" lazy-init="false" />
  10. <!-- 另外最好还要加入DefaultAnnotationHandlerMapping,不然会被 XML或其它的映射覆盖! -->
  11. <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
  12. <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
  13. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
  14. <!-- 支持上传文件  value表示上传文件的大小-->
  15. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  16. <property name="maxUploadSize" value="10000000000000"/></bean>
  17. </beans>

UploadAction.java

  1. package com.codeif.action;
  2. import java.io.File;
  3. import java.util.Date;
  4. import javax.servlet.http.HttpServletRequest;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.ui.ModelMap;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.multipart.MultipartFile;
  10. @Controller
  11. public class UploadAction {
  12. @RequestMapping(value = "/upload.do")
  13. public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
  14. System.out.println("开始");
  15. String path = request.getSession().getServletContext().getRealPath("upload");
  16. String fileName = file.getOriginalFilename();
  17. //        String fileName = new Date().getTime()+".jpg";
  18. System.out.println(path);
  19. File targetFile = new File(path, fileName);
  20. if(!targetFile.exists()){
  21. targetFile.mkdirs();
  22. }
  23. //保存
  24. try {
  25. // file.transferTo(targetFile);
  26. //也可以用这种方式,上面的方式能上传,但是老是报输出流被占用的错误。
  27. SaveFileFromInputStream(
          file.getInputStream(), realPath + filePath, name + "."+ fileType);
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);
  32. return "result";
  33. }
  34. }

SaveFileFromInputStream()的实现如下:

public void SaveFileFromInputStream(InputStream stream, String path,
   String filename) throws IOException {
   {      //path + "/"+ filename
    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();     
      }

index.jsp

  1. <%@ page pageEncoding="utf-8"%>
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <title>上传图片</title>
  7. </head>
  8. <body>
  9. <form action="upload.do" method="post" enctype="multipart/form-data">
  10. <input type="file" name="file" /> <input type="submit" value="Submit" /></form>
  11. </body>
  12. </html>