jsp页面给一个form表单提交文件
<form action="/user/upload" method="post" enctype="multipart/form-data">
<input id="File1" name="fileupload" multiple="multiple" type="file" value="" />
<input type="submit" value="上传" />
</form>
controller
/**
* 保存上传的文件
* @param request the request
* @param response the response
*/
@RequestMapping(value = "upload",method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response){
String name = userService.upload(request);
if(name != null){
super.setFormJson(response,true,name,"文件上传成功!");
}else{
super.setFormJson(response,false,name,"文件上传失败!");
}
}
serverImpl
/**
* 上传文件
* @param request
*/
public String upload(HttpServletRequest request){
try{
/*普通request是无法解析请求中的文件的。
MultipartHttpServletRequest是springmvc框架中的一个接口,默认实现类是DefaultMultipartHttpServletRequest*/
DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;
//读取文件,fileupload是前台jsp文件选择框中的name
List<MultipartFile> files = multipartRequest.getFiles("fileupload");
//上传文件
String name = "";
for(MultipartFile multiparfile:files){
name += ","+FileUtil.save(multiparfile, "D://360Downloads");
}
return name.substring(1);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
FileUtil.java
/**
* 保存文件到本地
*
* @param muliRequest the muli request
* @param path the path
* @return 返回文件名称 “file1,file2,file3”
*/
public static String save(MultipartFile muliRequest, String path) {
String filenames = "";
try {
//创建file对象 path可以为文件也可以为文件夹
File outputFile = new File(path);
//文件夹不存在-创建
if (!outputFile.exists()) {
outputFile.mkdirs();
}
//获得输入流
InputStream bis = muliRequest.getInputStream();
//文件名
String originalFilename = muliRequest.getOriginalFilename();
//文件后缀
String suffix = "";
if(originalFilename.lastIndexOf(".") != -1){
suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
}
//String filename = MD5.getUUID()+suffix;
String filename = originalFilename;
//文件储存的全路径
filenames = path+"/"+filename;
System.out.println(filename);
//创建文件输出流
FileOutputStream fos = new FileOutputStream(new File(
path,filename));
BufferedOutputStream bos = new BufferedOutputStream(fos);
Streams.copy(bis, bos, true);
} catch (IOException e) {
e.printStackTrace();
}
return filenames;
}