ssm ajax上传文件
时间: 2023-07-25 15:23:28 浏览: 100
首先,在前端页面上添加文件上传的表单,代码如下:
```html
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="button" value="上传" onclick="uploadFile()"/>
</form>
```
然后,在JavaScript代码中编写上传文件的函数,使用Ajax方式上传文件。代码如下:
```javascript
function uploadFile() {
var formData = new FormData($("#uploadForm")[0]);
$.ajax({
url: "uploadFile",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (data) {
alert("上传成功!");
},
error: function (xhr) {
alert("上传失败!");
}
});
}
```
接着,在Spring MVC的Controller中添加文件上传的处理方法,代码如下:
```java
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public String uploadFile(HttpServletRequest request) throws IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");
String fileName = file.getOriginalFilename();
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return "success";
}
```
最后,需要在Spring MVC的配置文件中添加以下配置,以支持文件上传:
```xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="104857600"/>
<property name="maxInMemorySize" value="4096"/>
</bean>
```
其中,maxUploadSize表示上传文件的最大大小,单位为字节。
阅读全文