Chinaunix首页 | 论坛 | 博客
  • 博客访问: 328143
  • 博文数量: 84
  • 博客积分: 886
  • 博客等级: 准尉
  • 技术积分: 769
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-30 19:32
文章分类

全部博文(84)

文章存档

2018年(1)

2017年(2)

2014年(1)

2013年(50)

2012年(30)

我的朋友

分类: Java

2013-10-28 12:27:37

转自:http://blog.csdn.net/qingwaxw1980/article/details/5017420

一、配置

1、*-servlet.xml  (WebApploicationContext)

  1. <!-- file upload -->
  2.     <bean id="multipartResolver"
  3.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  4.         <property name="maxUploadSize" value="5000000" />
  5.         <property name="maxInMemorySize" value="4096" />
  6.         <property name="defaultEncoding" value="GBK" />
  7.     </bean>
注意下面的commandClass值,


  1. <!-- === excel文件上传页面 === -->
  2.     <bean name="/excelupload.do" class="test.ExcelUpload">
  3.         <property name="formView" value="atest" />
  4.         <property name="successView" value="atest" />
  5.         <property name="commandName" value="upload" />
  6.         <property name="commandClass" value="test.UploadDTO" />
  7.     </bean>

二、代码

1、使用MultipartFile

  1. import java.io.Serializable;

  2. import org.springframework.web.multipart.MultipartFile;

  3. public class UploadDTO implements Serializable {

  4.     private MultipartFile file;

  5.     /**
  6.      * @return Returns the file.
  7.      */
  8.     public MultipartFile getFile() {
  9.         return file;
  10.     }

  11.     /**
  12.      * @param file The file to set.
  13.      */
  14.     public void setFile(MultipartFile file) {
  15.         this.file = file;
  16.     }


  17. }

  1. import java.io.FileOutputStream;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.ArrayList;
  5. import java.util.Date;
  6. import java.util.Enumeration;
  7. import java.util.Iterator;
  8. import java.util.List;

  9. import javax.servlet.ServletException;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;

  12. import org.apache.poi.hssf.usermodel.HSSFCell;
  13. import org.apache.poi.hssf.usermodel.HSSFRow;
  14. import org.apache.poi.hssf.usermodel.HSSFSheet;
  15. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  16. import org.springframework.validation.BindException;
  17. import org.springframework.web.bind.ServletRequestDataBinder;
  18. import org.springframework.web.multipart.MultipartFile;
  19. import org.springframework.web.multipart.MultipartHttpServletRequest;
  20. import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
  21. import org.springframework.web.servlet.ModelAndView;
  22. import org.springframework.web.servlet.mvc.SimpleFormController;

  23. public class ExcelUpload extends SimpleFormController {

  24.     protected ModelAndView onSubmit(HttpServletRequest request,
  25.             HttpServletResponse response, Object command, BindException errors)
  26.             throws Exception {
  27.         logger.info("Excel upload=================================start");

  28.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  29.         MultipartFile multipartFile = multipartRequest.getFile("file");

  30.         Enumeration names = request.getParameterNames();
  31.         while (names.hasMoreElements()) {
  32.             String name = (String) names.nextElement();
  33.             logger.debug(name+"="+request.getParameter(name));
  34.         }
  35.         
  36.         
  37.         logger.info("Excel upload=================================end");
  38.         return super.onSubmit(request, response, command, errors);

  39.     }
  40. }
2、不使用MultipartFile

  1. import java.io.Serializable;

  2. import org.springframework.web.multipart.MultipartFile;

  3. public class UploadDTO implements Serializable {

  4.     private byte[] file;

  5.     /**
  6.      * @return Returns the file.
  7.      */
  8.     public byte[] getFile() {
  9.         return file;
  10.     }

  11.     /**
  12.      * @param file The file to set.
  13.      */
  14.     public void setFile(byte[] file) {
  15.         this.file = file;
  16.     }


  17. }


  1. public class ExcelUpload extends SimpleFormController {
  2.     protected void initBinder(HttpServletRequest request,
  3.             ServletRequestDataBinder binder) throws ServletException {
  4.         binder.registerCustomEditor(byte[].class,
  5.                 new ByteArrayMultipartFileEditor());
  6.     }
  7.     protected ModelAndView onSubmit(HttpServletRequest request,
  8.             HttpServletResponse response, Object command, BindException errors)
  9.             throws Exception {
  10.         logger.info("Excel upload=================================start");

  11.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  12.         MultipartFile multipartFile = multipartRequest.getFile("file");

  13.         logger.debug(Long.toString(multipartFile.getSize()));
  14.         logger.info("Excel upload=================================end");
  15.         return super.onSubmit(request, response, command, errors);

  16.     }
  17. }

附:

1、另存上传文件


  1. public void SaveFileFromInputStream(InputStream stream, String path,
  2.             String filename) throws IOException {
  3.         FileOutputStream fs = new FileOutputStream(path + "/" + filename);
  4.         byte[] buffer = new byte[1024 * 1024];
  5.         int bytesum = 0;
  6.         int byteread = 0;
  7.         while ((byteread = stream.read(buffer)) != -1) {
  8.             bytesum += byteread;
  9.             fs.write(buffer, 0, byteread);
  10.             fs.flush();
  11.         }
  12.         fs.close();
  13.         stream.close();
  14.     }

2、Excel文件处理(POI - 2.5)

  1. private int getTargetList(MultipartFile multipartFile,
  2.             HttpServletRequest request, Date insuranceBeginTime, String planCode)
  3.             throws Exception {
  4.         String fileType = "";
  5.         try {
  6.             String fileName = multipartFile.getOriginalFilename();
  7.             fileType = fileName.substring(fileName.lastIndexOf(".") + 1,
  8.                     fileName.lastIndexOf(".") + 4);
  9.         } catch (Exception e) {
  10.             logger.error(e);
  11.             fileType = "";
  12.         }
  13.         if (!fileType.toLowerCase().equals("xls")) {
  14.             // throw new BusinessServiceException("导入的文件格式不正确,应该不是excel文件");
  15.             this.logger.debug("导入的文件格式不正确,应该不是excel文件");
  16.             return 0;
  17.         }
  18.         HSSFWorkbook wb = null;
  19.         try {
  20.             wb = new HSSFWorkbook(multipartFile.getInputStream());
  21.             // logger.debug(wb.getNumberOfSheets());
  22.             HSSFSheet sheet = wb.getSheetAt(0);
  23.             logger.debug("sheet name = "+wb.getSheetName(0));
  24.             for(int i = sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++){
  25.                 HSSFRow row = sheet.getRow(i);
  26.                 Iterator cells = row.cellIterator();
  27.                 while(cells.hasNext()){
  28.                     HSSFCell cell = (HSSFCell) cells.next();                    
  29.                     logger.debug(cell.getStringCellValue());                    
  30.                 }
  31.             }
  32.             logger.debug("last row = "+sheet.getLastRowNum());
  33.             
  34.             return wb.getNumberOfSheets();
  35. //            return sheet.getFirstRowNum();
  36.         } catch (Exception e) {
  37.             logger.error(e);
  38.             // throw new
  39.             // BusinessServiceException("未知原因!保存Excel文件时,请不要将鼠标最终定位在Excel中的可以下拉选值的列上。");
  40.         }
  41.         // ApplicationContext ctx =
  42.         // ApplicationWebContexton.getInstance(request);
  43.         // IImportExcelTarget excelParser = (IImportExcelTarget)
  44.         // ctx.getBean(planCode);
  45.         // return excelParser.getTargetList(wb, request,
  46.         // insuranceBeginTime,planCode);
  47.         return 0;
  48.     }

3、request.parameters = 与上传文件同表单的 field value

  1. <form action="excelupload.do" method="post" enctype="multipart/form-data" name="form1">
  2.   <table width="100%" border="0" cellspacing="1" cellpadding="0">
  3.     <tr>
  4.       <td>&nbsp;</td>
  5.       <td>&nbsp;</td>
  6.       <td>&nbsp;</td>
  7.     </tr>
  8.     <tr>
  9.       <td>&nbsp;</td>
  10.       <td><label>上传
  11.           <input type="file" name="file">
  12.       </label></td>
  13.       <td>&nbsp;</td>
  14.     </tr>
  15.     <tr>
  16.       <td>&nbsp;</td>
  17.       <td>&nbsp;<input name="assas" type="text" id="assas" value="asdsadas">
  18.       <input type="submit" name="Submit" value="提交"></td>
  19.       <td>&nbsp;</td>
  20.     </tr>
  21.   </table>
  22. </form>






阅读(10454) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~