这是一个使用ajax调用的spring项目。我想将上传的图像保存在resources / images文件夹中。这是我的控制器:
@Controller
//@RequestMapping("/cont")
public class RestController {
@RequestMapping(value = "/echofile", method = RequestMethod.POST)
public @ResponseBody HashMap<String, Object> echoFile(MultipartHttpServletRequest request,
HttpServletResponse response) throws Exception {
InputStream inputStream = null;
OutputStream outputStream = null;
UploadedFile upldfile = new UploadedFile();
MultipartFile multipartFile = request.getFile("file");
upldfile.setFile(multipartFile);
String fileName = multipartFile.getOriginalFilename();
Long size = multipartFile.getSize();
String contentType = multipartFile.getContentType();
InputStream stream = multipartFile.getInputStream();
byte[] bytes = IOUtils.toByteArray(stream);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("fileoriginalsize", size);
map.put("contenttype", contentType);
map.put("base64", new String(Base64Utils.encode(bytes)));
try {
inputStream = ((MultipartFile) upldfile).getInputStream();
File newFile = new File("E:/Java Project/SimpleAjaxJqueryPicUpload/src/main/resources/images" + fileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
// byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
文件已上传并显示在index.jsp中。但是它不存储在resources / images文件夹中。
这是我的index.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC - Upload File</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
var isJpg = function(name) {
return name.match(/jpg$/i)
};
var isPng = function(name) {
return name.match(/png$/i)
};
$(document).ready(function() {
var file = $('[name="file"]');
var imgContainer = $('#imgContainer');
var formData = new FormData();
formData.append('file', jQuery('input[type=file]')[0].files[0]);
$('#btnUpload').on('click', function() {
var filename = $.trim(file.val());
if (!(isJpg(filename) || isPng(filename))) {
alert('Please browse a JPG/PNG file to upload ...');
return;
}
$.ajax({
url: "http://localhost:8080/SimpleAjaxJqueryPicUpload/api/echofile",
type: "POST",
/* data: new FormData(document.getElementById("fileForm")), */
data: formData,
enctype: 'multipart/form-data',
processData: false,
contentType: false
}).done(function(data) {
imgContainer.html('');
var img = '<img src="data:' + data.contenttype + ';base64,'
+ data.base64 + '"/>';
imgContainer.append(img);
}).fail(function(jqXHR, textStatus) {
//alert(jqXHR.responseText);
alert('File upload failed ...');
});
});
$('#btnClear').on('click', function() {
imgContainer.html('');
file.val('');
});
});
</script>
</head>
<body>
<body style="font-family: calibri; font-size: 8pt">
<div>
<div id="fileForm">
<input type="file" name="file" id="image"/>
<button id="btnUpload" type="button">Upload file</button>
<button id="btnClear" type="button">Clear</button>
</div>
<div id="imgContainer"></div>
</div>
</body>
</html>
模型是:
package SimpleAjaxJqueryPicUpload.model;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class UploadedFile {
public int length;
public byte[] bytes;
public String name;
public String type;
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
显示错误:
SEVERE:Servlet [dispatcher]中的Servlet.service()路径[/ SimpleAjaxJqueryPicUpload]抛出异常[请求处理失败嵌套的异常是java.lang.ClassCastException:无法将SimpleAjaxJqueryPicUpload.model.UploadedFile强制转换为org.springframework.web.multipart.MultipartFile]的根本原因java.lang.ClassCastException:无法将SimpleAjaxJqueryPicUpload.model.UploadedFile强制转换为org.springframework.web.multipart.MultipartFile位于SimpleAjaxJqueryPicUpload.controller.RestController.echoFile(RestController.java:68)在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处sun.reflect.NativeMethodAccessorImpl.invoke(未知来源)位于sun.reflect.DelegatingMethodAccessorImpl.invoke(未知源)位于java.lang.reflect.Method.invoke(来源未知)org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)在org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)在org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)在org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)在org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)在org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)在org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)在javax.servlet.http.HttpServlet.service(HttpServlet.java:648)处org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)在javax.servlet.http.HttpServlet.service(HttpServlet.java:729)在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)在org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)在org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)在org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)在org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)在org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)在org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)在org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)在org.apache.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:745)在org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1437)在org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)在java.util.concurrent.ThreadPoolExecutor.runWorker(未知来源)在java.util.concurrent.ThreadPoolExecutor $ Worker.run(未知来源)在org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)在java.lang.Thread.run(未知来源)
我的dispatcher-servlet.xml是:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:component-scan base-package="SimpleAjaxJqueryPicUpload.controller" />
<mvc:annotation-driven />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"/>
</bean>
</beans>
问题出在哪里?
我已经解决了这个问题。我必须改变几件事。1.我必须更改ajax调用。
url: "http://localhost:8080/SimpleAjaxJqueryPicUpload/api/echofile",
type: "POST",
data: formData,
enctype: 'multipart/form-data',
processData: false,
modelAttribute:'uploadedFile',
contentType: false
我必须添加modelAttribute:'uploadedFile'
然后我更改了控制器。我的控制器是:
@ Controller// @ RequestMapping(“ / cont”)公共类RestController {
@RequestMapping(value = "/echofile", method = RequestMethod.POST)
public @ResponseBody HashMap<String, Object> echoFile(MultipartHttpServletRequest request,
HttpServletResponse response , @ModelAttribute("uploadedFile") UploadedFile upldfile) throws Exception {
InputStream inputStream = null;
OutputStream outputStream = null;
MultipartFile multipartFile = request.getFile("file");
MultipartFile file = upldfile.getFile();
String fileName = file.getOriginalFilename();
upldfile.setFile(file);
String fileName2 = multipartFile.getOriginalFilename();
Long size = multipartFile.getSize();
String contentType = multipartFile.getContentType();
InputStream stream = multipartFile.getInputStream();
byte[] bytes = IOUtils.toByteArray(stream);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("fileoriginalsize", size);
map.put("contenttype", contentType);
map.put("base64", new String(Base64Utils.encode(bytes)));
try {
// inputStream = ((MultipartFile) upldfile).getInputStream();
inputStream = file.getInputStream();
File newFile = new File("E:/Java Project/SimpleAjaxJqueryPicUpload/src/main/resources/images/" + fileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
// byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
然后问题已解决!!!!!!!!! :D