<h3>File to upload</h3>
<form action ="upload" method="post" enctype="multipart/form-data">
<input type ="file" name ="file">
<input type ="submit" value ="submit">
</form>
这是我的控制器
@RequestMapping(value="/upload",method=RequestMethod.POST)
public ModelAndView upload(@RequestParam("file") CommonsMultipartFile file,HttpSession session) throws IOException
{
String path = session.getServletContext().getRealPath("/");
String filename=file.getOriginalFilename();
ImagePOJO pojo = new ImagePOJO();
byte barr[]=file.getBytes();
pojo.setPath(path);
pojo.setFilename(filename);
//String q = pojo.setPath(path)+"/"+pojo.setFilename(filename);
String w = pojo.getPath()+""+pojo.getFilename();
//System.out.println(Arrays.toString(barr));
System.out.println(path+" "+filename);
System.out.println(w);
BufferedOutputStream bout;
try {
bout = new BufferedOutputStream(new FileOutputStream(path+"/"+filename));
Object o = bout;
bout.write(barr);
bout.flush();
bout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}[enter image description here][1]
发布于 2018-05-04 06:04:53
你为什么不试试Spring Content呢?
在http://start.spring.io/上自己生成一个spring boot应用程序。
将这些依赖项添加到您的pom。
pom.xml
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-fs-boot-starter</artifactId>
<version>0.0.11</version>
</dependency>
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-rest-boot-starter</artifactId>
<version>0.0.11</version>
</dependency>
将UploadStore
添加到您的主类:
SpringBootApplication.java
@SpringBootApplication
public class SpringContentApplication {
public static void main(String[] args) {
SpringApplication.run(SpringContentApplication.class, args);
}
@StoreRestResource(path="upload")
public interface UploadStore extends Store<String> {
}
}
每个上传的文件都需要一个惟一的名称,所以让我们生成一个guid并动态设置表单的操作。如下所示更新html:
form.html
<script language="JavaScript">
window.onload = function() {
document.myform.action = get_action();
}
function get_action() {
return "upload/" + guidGenerator();
}
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
</script>
<html>
<body>
<h3>File to upload</h3>
<form name=myform method="post" enctype="multipart/form-data">
<input type ="file" name ="file">
<input type ="submit" value ="submit">
</form>
</body>
</html>
运行您的应用程序并为UploadStore指定一个位置:
java -jar yourapp.jar --spring.content.fs.filesystemRoot=/path/to/your/store
UploadStore
和upload
不是很好的名字,因为这是一个全功能的内容服务,支持POST,PUT,GET和DELETE。GET even支持视频流。
也可以让UploadStore实现Renderable
来获取上传内容的格式副本;例如,获取上传的word文档的格式。
和/或Searchable
来启用全文索引(但这也需要Apache Solr)。
它可以与Spring Data结合使用,允许您将Spring数据实体和Spring内容资源关联起来。
HTH
https://stackoverflow.com/questions/49993737
复制相似问题