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

前端:

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

</head>
<body>
<fieldset class=\"layui-elem-field layui-field- \" 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>
< >
    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); //图片链接( 64)
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.code > 0){
                    return  .msg(\'上传失败\');
                }
                //上传成功
            }
 
        });
 
    });
</ >
</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.JSON ;

import org.spring work.stereotype.Controller;
import org.spring work.web.bind.annotation.RequestMapping;
import org.spring work.web.bind.annotation.RequestParam;
import org.spring work.web.bind.annotation.ResponseBody;
import org.spring work.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();
	            }
	            JSON  result = new JSON ();
	            result.put(\"fileUrl\", \"/img/\"+time+fileName);
	            result.put(\"url\", \"/img/\"+time+fileName);
	            result.put(\"state\", \"SUCCESS\");
	            result.put(\" \", fileName);
	            result.put(\"original\", fileName);
	            result.put(\"type\", suffix);
	            result.put(\"size\", size);
	            return result.toString();
	        }else{
	            JSON  result = new JSON ();
	            result.put(\"ss\", false);
	            result.put(\"msg\", \"格式不支持\");
	            return result.toString();
	        }
	 
	    }

}

spring-mvc- :

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

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


<bean id=\"viewResolver\" class=\"org.spring work.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.spring work.stereotype.Controller;
import org.spring work.ui.Model;
import org.spring work.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. :

<?  version=\"1.0\" encoding=\"UTF-8\"?>
<web-app version=\"3.0\" 
	 ns=\"http://java.sun.com/ /ns/javaee\" 
	 ns:xsi=\"http://www.w3.org/2001/ Schema-instance\" 
	xsi:schemaLocation=\"http://java.sun.com/ /ns/javaee 
	http://java.sun.com/ /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.spring work.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc. </param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

收藏 打印