spring-layui-图片上传预览

花了三天三夜的时间终于研究出来了
原文:使用 MultipartFile 实现图片上传功能

前端:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>文件上传demo</title>
    
   <script src="http://layui.hcwl520.com.cn/layui/layui.js?v=201809030202"></script>
  <link rel="stylesheet"  href="http://layui.hcwl520.com.cn/layui/css/layui.css?v=201809030202"/>

</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend>常规使用:普通图片上传</legend>
</fieldset>
<div class="layui-upload">
    <button type="button" class="layui-btn" id="test1">上传图片</button>
    <div class="layui-upload-list">
        <img class="layui-upload-img" id="demo1">
        <p id="demoText"></p>
    </div>
</div>
</body>
<script>
    layui.use(['form','upload'],function(exports) {
        var form = layui.form;
        var $ = layui.jquery;
        var upload = layui.upload;
        upload.render({
            elem: '#test1'
            ,url: '/load/upload'
            ,before: function(obj){
                //预读本地文件示例,不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result); //图片链接(base64)
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.code > 0){
                    return layer.msg('上传失败');
                }
                //上传成功
            }
 
        });
 
    });
</script>
</html>

后端:

package com.demo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.UUID;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class Load {
    
	  @RequestMapping(value = "/upload")
	    @ResponseBody
	    public String upload( MultipartFile file, HttpServletRequest request) {
		  //System.out.println("file"+file);
	        Calendar currTime = Calendar.getInstance();
	        String time = String.valueOf(currTime.get(Calendar.YEAR))+String.valueOf((currTime.get(Calendar.MONTH)+1));
	        String path ="d:"+File.separator+"img"+File.separator+time;
	        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
	        suffix = suffix.toLowerCase();
	        if(suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png") || suffix.equals(".gif")){
	            String fileName = UUID.randomUUID().toString()+suffix;
	            File targetFile = new File(path, fileName);
	            if(!targetFile.getParentFile().exists()){//注意,判断父级路径是否存在
	                targetFile.getParentFile().mkdirs();
	            }
	            long size = 0;
	            //保存
	            try {
	                file.transferTo(targetFile);
	                size = file.getSize();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	            JSONObject result = new JSONObject();
	            result.put("fileUrl", "/img/"+time+fileName);
	            result.put("url", "/img/"+time+fileName);
	            result.put("state", "SUCCESS");
	            result.put("title", fileName);
	            result.put("original", fileName);
	            result.put("type", suffix);
	            result.put("size", size);
	            return result.toString();
	        }else{
	            JSONObject result = new JSONObject();
	            result.put("ss", false);
	            result.put("msg", "格式不支持");
	            return result.toString();
	        }
	 
	    }

}

spring-mvc-xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!--   自动扫描加载注解的包 -->
<context:component-scan base-package="com.demo"/>

    <bean name="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="5834689" />
    </bean>


<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp" ></property>
</bean>

</beans>

controller:

package com.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Testhello{
    @RequestMapping("/hello")      //对应于index.jsp的hello请求
 public String hello(Model model) {
     model.addAttribute("message", "我是springmvc");
    return "hello";                      //返回到view的hello.jsp
    // TODO Auto-generated method stub
}
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name>springmvc01</display-name>
  <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_mmp14948

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值