zoukankan      html  css  js  c++  java
  • springmvc 上传图片

    package controller;
    
    import java.io.File;
    import java.io.IOException;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.commons.lang.xwork.RandomStringUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
    
    import pojo.UploadedImageFile;
    
    @Controller
    public class UploadController {
    	
    	@RequestMapping("/uploadImage")
    	
    	//方法的第二个参数UploadedImageFile 中已经注入好了 image
    	public ModelAndView upload(HttpServletRequest request,
    			UploadedImageFile file) throws IllegalStateException, IOException {
    		
    		//通过 RandomStringUtils.randomAlphanumeric(10);获取一个随机文件名。 因为用户可能上传相同文件名的文件,为了不覆盖原来的文件,通过随机文件名的办法来规避
    		String name = RandomStringUtils.randomAlphanumeric(10);
    		String newFileName = name + ".jpg";
    		
    		//request.getServletContext().getRealPath("/image") 
    				//根据request.getServletContext().getRealPath 获取到web目录下的image目录,用于存放上传后的文件。
    		File newFile = new File(request.getServletContext().getRealPath(
    				"/image"), newFileName);  
    		
    		
    		
    		System.out.println(newFile);
    		System.out.println(newFile.getParentFile());
    		newFile.getParentFile().mkdirs();
    		
    		//调用file.getImage().transferTo(newFile); 复制文件
    		file.getImage().transferTo(newFile);
    
    		ModelAndView mav = new ModelAndView("showUploadedFile");
    		mav.addObject("imageName", newFileName);
    		return mav;
    	}
    }
    

    上面2个输出语句的打印如下

    信息: Starting ProtocolHandler ["http-bio-8080"]
    六月 01, 2018 5:12:52 下午 org.apache.coyote.AbstractProtocol start
    信息: Starting ProtocolHandler ["ajp-bio-8009"]
    六月 01, 2018 5:12:52 下午 org.apache.catalina.startup.Catalina start
    信息: Server startup in 4227 ms
    C:Userschenworkspace.metadata.pluginsorg.eclipse.wst.server.core	mp1wtpwebappsspringmvcimagex6Cf5WOFyZ.jpg
    C:Userschenworkspace.metadata.pluginsorg.eclipse.wst.server.core	mp1wtpwebappsspringmvcimage
    

    新建类UploadController 作为上传控制器
    准备方法upload 映射上传路径/uploadImage

    1. 方法的第二个参数UploadedImageFile 中已经注入好了 image
    2. 通过 RandomStringUtils.randomAlphanumeric(10);获取一个随机文件名。 因为用户可能上传相同文件名的文件,为了不覆盖原来的文件,通过随机文件名的办法来规避
    3. 根据request.getServletContext().getRealPath 获取到webContent目录下的image目录,用于存放上传后的文件。
    4. 调用file.getImage().transferTo(newFile); 复制文件
    5. 把生成的随机文件名提交给视图,用于后续的显示

  • 相关阅读:
    nyoj999 师傅又被妖怪抓走了 (预处理+bfs+状态压缩)
    使用逆波兰式进行表达式求值
    [moses笔记]编译含有nplm的moses解码器
    菲波那契数列编程实现
    引领网页设计潮流的优秀网页作品赏析
    MFC中获取各个窗口之间的句柄或者指针对象的方法
    UVALive 6529 Eleven 区间dp
    jquery 实现菜单的下拉菜单
    数字图像和视频处理的基础-第4周运动预计matlab练习题
    setjmp与longjmp
  • 原文地址:https://www.cnblogs.com/czy16/p/9123525.html
Copyright © 2011-2022 走看看