本文共 2054 字,大约阅读时间需要 6 分钟。
方式一:
1.spring配置文件
2.上传页面jsp
3.Controller类
package com.skymr.mvc.controller.annotation;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.commons.CommonsMultipartFile;@Controller@RequestMapping("file")public class UploadController { @RequestMapping("/upload") public String upload(@RequestParam("file")CommonsMultipartFile file){ String fileName = file.getOriginalFilename(); System.out.println("收到上传文件" + fileName); if(file.isEmpty()){ System.out.println("上传失败"); } try { InputStream is = file.getInputStream(); FileOutputStream fos = new FileOutputStream("E:/"+fileName); int b; while((b=is.read()) != -1){ fos.write(b); } fos.flush(); fos.close(); is.close(); } catch (IOException e) { } return "uploadSuc"; } @RequestMapping("/uploadView") public String uploadView(){ return "uploadView"; }}部署测试后能上传成功,但上传较大文件时抛出异常,却不知道在哪捕获.
方式二:使用springmvc扩展的HttpServletReqeust,MultipartHttpServletRequest
@RequestMapping("/upload2") public String upload2(HttpServletRequest request, HttpServletResponse response){ //解析器 CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext()); if(resolver.isMultipart(request)){ MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; Iteratoriter = multiRequest.getFileNames(); while(iter.hasNext()){ String name = iter.next(); MultipartFile file = multiRequest.getFile(name); try { System.out.println("收到上传文件" + file.getOriginalFilename()); file.transferTo(new File("E:/"+file.getOriginalFilename())); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } return "uploadSuc"; }
转载地址:http://mjihj.baihongyu.com/