花了三天三夜的时间终于研究出来了
原文:使用 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>