问题
在使用Spring MVC进行文件上传时,文件上传成功,但是返回json给页面时报错404。
解决方法
由于前端页面只有一个html文件,使用@ResponseBody声明返回值。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- 对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 需要更改 -->
<context:component-scan base-package="com.clustertech.opencv.controller" />
<context:component-scan base-package="com.clustertech.opencv.service" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<mvc:annotation-driven />
<mvc:resources mapping="/pic.html" location="/pic.html" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 对文件上传的处理,这里声明的id必须为multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- 最大为100M,单位为字节 -->
<property name="maxUploadSize" value="104857600"></property>
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<servlet>
<servlet-name>opencv-img</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>opencv-img</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>pic.html</welcome-file>
</welcome-file-list>
</web-app>
package com.clustertech.opencv.controller;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.clustertech.opencv.service.ImageService;
@Controller
@RequestMapping("/image")
public class ImageController {
@Autowired
private ImageService imageService;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String imgUpload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
String realUploadPath = "/opt/tomcat/webapps/ROOT/images";
String imageUrl = null;
BufferedImage bi = null;
try {
imageUrl = imageService.uploadImage(file, realUploadPath);
ServletOutputStream out = response.getOutputStream();
bi = ImageIO.read(new File(imageUrl));
ImageIO.write(bi, "jpg", out);
} catch (IOException e) {
e.printStackTrace();
}
return imageUrl;
}
// 文件下载
@RequestMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
String path = request.getServletContext().getRealPath("/") + "/images/rawImages/";
String fileName = request.getParameter("filename");
File file = new File(path + fileName);
if (file.exists()) {
response.setContentType("application/octet-stream");
response.addHeader("Content-disposition",
"attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
byte[] bs = new byte[1024];
while ((inputStream.read(bs) > 0)) {
outputStream.write(bs);
}
outputStream.close();
inputStream.close();
}
}
}
package com.clustertech.opencv.service;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service("imageService")
public class ImageService {
public String uploadImage(MultipartFile file, String realUploadPath) throws IOException {
File uploadFile = new File(realUploadPath + "/rawImages");
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
InputStream inputStream = file.getInputStream();
String outputPath = realUploadPath + "/rawImages/" + file.getOriginalFilename();
OutputStream outputStream = new FileOutputStream(outputPath);
byte[] buffer = new byte[1024];
while ((inputStream.read(buffer)) > 0) {
outputStream.write(buffer);
}
outputStream.close();
return realUploadPath + "/rawImages/" + file.getOriginalFilename();
}
}
<html>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style type="text/css">
#picShowWrapper{
height: 500px;
width: 500px;
border: 1px solid #ccc;
}
.btnsWrapper{
display: flex;
}
</style>
<script language="javascript">
function uploadPic() {
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: '/image/upload',
type: 'post',
data: formData,
processData: false,
contentType: false,
success: function(response) {
$("#rawPic").attr("src", '/images/rawImages/pic1.jpg');
// console.log(response);
}
});
}
function uploadPictest() {
$.ajax({
url: '/image/test',
type: 'get',
processData: false,
contentType: false,
success: function(response) {
console.log(response);
// $("#rawPic").attr("src","data:image/png;base64," + response);
}
});
}
function changeImg(optionData) {
console.log(optionData);
}
</script>
</head>
<body>
<!-- <div id="picShowWrapper"> -->
<!-- <iframe id="uploadPic" name="uploadPic_iframe"></iframe> -->
<div class="leftRawPic">
<img id="rawPic" width="400" height="400" />
<img id="changedPic" width="400" height="400" />
</div>
<!-- </div> -->
<!-- <form target="uploadPic_iframe"> -->
<form>
<div class="btnsWrapper">
<input type="file" name="image" id="file"/>
<input type="button" value="确认上传" onclick="uploadPic()" />
<input type="button" value="test" onclick="uploadPictest()" />
<div>
<select onchange="changeImg(this.value);">
<option value="noFog">去雾</option>
<option value="chushi">除湿</option>
<option value="jiangzao">降噪</option>
</select>
</div>
</div>
</form>
</body>
</html>