温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

详解SpringMVC实现图片上传以及该注意的小细节

发布时间:2020-08-25 22:13:31 来源:脚本之家 阅读:116 作者:JustCode 栏目:编程语言

先附上图片上传的代码

jsp代码如下:

<form action="${path}/upload/uploadPic.do" method="post" enctype="multipart/form-data">   
<div>
    ![](${path}/mall/image/load_image.png)
    <input type="file" id="input-image" name="input-image">
    <input id="input-relative-path" name="imgs" type="hidden" >
    <input id="input-last-path" type="hidden">
    <input type="submit" value="上传图片">
 </div>
</form>

controller代码:通过spring的方式实现

@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {
  @RequestMapping(value = "/uploadPic", method = RequestMethod.POST)
  @LoginCheck
  public void uploadPic(HttpServletRequest request, PrintWriter out, String lastRealPath) throws IOException {
    // 将当前上下文初始化给CommonsMultipartResolver
    CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    // 检查form中是否有enctype="multipart/form-data"
    if (resolver.isMultipart(request)) {
      // 强制转化request
      MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
      // 从表单获取input名称
      Iterator<String> iterable = req.getFileNames();
      // 存在文件
      if (iterable.hasNext()) {
        String inputName = iterable.next();
        // 获得文件
        MultipartFile mf = req.getFile(inputName);
        byte[] mfs = mf.getBytes();
        // 定义文件名
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
          fileName = fileName + random.nextInt(10);
        }
        // 获得后缀名
        String oriFileName = mf.getOriginalFilename();
        String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));

        // 上传图片到本地
        String localPath = "/Users/ZR/Desktop/webPro/console/src/main/webapp/image/" + fileName + suffix;
        mf.transferTo(new File(localPath));

        // 获取图片的宽高
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(new File(localPath)));
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        // 获取文件大小
        long size = mf.getSize();
      }
    }
  }
}

spring-mvc.xml代码:

 <!--
  文件上传的视图解析器,id值是固定的
 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="maxUploadSize" value="1024000"/>
  <!-- 其他属性 -->
</bean>

功能的实现其实很简单,但是对于初学者还是需要注意如下几个点

  • form上的enctype="multipart/form-data"不能忘记。
  • <input type="file" onchange="submitUpload()" id="input-image" name="input-image"> 的name标签可以随便取名,但是不能忽略,否则Iterator<String> iterable = req.getFileNames();这边获取的集合将为空。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI