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:\Users\chen\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\springmvc\image\x6Cf5WOFyZ.jpg
C:\Users\chen\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\springmvc\image

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

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

1175089-20180601172017785-188098256.png

1175089-20180601172304232-306942477.png

1175089-20180601210935728-21055188.png

转载于:https://www.cnblogs.com/czy16/p/9123525.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值