[英]how to upload a file with springMVC restful service and jQuery
我正在开发一个使用springMVC Restful服务作为后端服务,使用jQuery作为前端技术的应用程序。
现在,我需要将文件通过Web服务上载到服务器。 我不知道如何编写这样的文件上传功能。 我应该如何通过jQuery将文件发送到服务器?
提前致谢。
我不确定您要的是什么,这是我从您那里得到的
像这样的控制器代码
map.put("a", "/Student_Photos/sample.jpg");
在jsp中写你的东西,包括这个
<form:form modelAttribute="uploadItem" action="add" name="student"
method="post" enctype="multipart/form-data"
onSubmit="return validate();">
<td width="152" rowspan="4" ><img id="blah"
src="<c:url value="${a}"/>" alt="your image" width="130"
height="110" />
<form:input path="fileData" id="image" type="file"
onchange="readURL(this)" /></td>
</form:form>
在浏览器中有两种主要方法:
对于现代浏览器,请使用HTML5 File API。 请参阅https://developer.mozilla.org/zh-CN/docs/Using_files_from_web_applications
如果需要支持旧的浏览器,则将文件发布到隐藏的iFrame中。 参见http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/
在服务器端,我将假设您正在对REST servlet使用Spring Data REST(SDR)。 SDR不会上传文件,但是您可以在同一Servlet中将SDR与常规的Spring MVC Dispatcher Servlet一起运行。
如果保存到数据库,则MVC Dispatcher的FileController中的处理程序方法将如下所示:
@RequestMapping(value = "/files", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
List<FileEntity> upload(@RequestParam("file") MultipartFile[] multipartFiles) throws Exception {
List<FileEntity> response = new ArrayList<FileEntity>();
for (MultipartFile multipartFile : multipartFiles) {
FileEntity f = new FileEntity(multipartFile.getBytes(), multipartFile.getContentType(), multipartFile.getOriginalFilename());
fileRepository.save(f);
response.add(f);
}
return response;
}
您需要在类路径上使用SDR,Apache Commons FileUpload和IO(或使用更新的Servlet 3 API代替Apache Commons)。 将它们添加为Maven依赖项:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.