SpringBoot 文件或图片上传与下载功能的实现
导入依赖(pom.xml)
commons-io commons-io 2.6 commons-fileupload commons-fileupload 1.3.3 javax.servlet javax.servlet-api 4.0.1 net.coobird thumbnailator 0.4.8
全局配置application.properties
#上传文件大小 spring.servlet.multipart.max-file-size=5MB spring.servlet.multipart.max-request-size=5MB
创建WebMvcConfig配置类 静态资源映射
@Configuration
publicclassWebMvcConfigimplementsWebMvcConfigurer{
@Override
publicvoidaddResourceHandlers(ResourceHandlerRegistryregistry){
ApplicationHomeh=newApplicationHome(getClass());
FilejarF=h.getSource();
StringdirPath=jarF.getParentFile().toString()+"/upload/";
Stringos=System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){//如果是Windows系统
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
}else{
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
}
}
}
文件或图片上传
控制层
//上传文件
@ResponseBody
@RequestMapping("/upload")
publicStringfileUpload(@RequestParam("files")MultipartFilefiles)throwsIOException{
////win系统上传路径保存设置
////获取项目路径
//FileprojectPath=newFile(ResourceUtils.getURL("classpath:").getPath());
////绝对路径=项目路径+自定义路径
//FilepathFile=newFile(projectPath.getAbsolutePath(),"static/upload/");
//if(!pathFile.exists()){
//pathFile.mkdirs();
//}
////上传文件地址
//UUIDuuid=UUID.randomUUID();
//FileserverFile=newFile(pathFile,uuid+"_"+files.getOriginalFilename());
//files.transferTo(serverFile);
//
//StringimgPath=("/upload/"+uuid+"_"+files.getOriginalFilename()).replace("\\","/");
//
//returnimgPath;
//Linux服务器上传路径保存设置
//项目路径/home/www/
FilepathFile=newFile("/home/www/upload/");
if(!pathFile.exists()){
pathFile.mkdirs();
}
//上传文件地址
UUIDuuid=UUID.randomUUID();
FileserverFile=newFile(pathFile,uuid+"_"+files.getOriginalFilename());
files.transferTo(serverFile);
StringimgPath=("/upload/"+uuid+"_"+files.getOriginalFilename()).replace("\\","/");
returnimgPath;
}
HTML页面
Ajax无刷新上传
上传图片
JS
//普通图片上传
$('#img_upload').click(function(){
varformData=newFormData();
//获取选择的文件
$.each($('input[name="files"]'),function(index,item){
formData.append("files",item.files[0])
});
//发送异步请求
$.ajax({
method:'post',
url:'[[@{/user/upload}]]',//文件上传接口
data:formData,
processData:false,
contentType:false,
success:function(data){
//成功返回触发的方法
$('#imgPath').val(data);
alert("上传成功");
},
//请求失败触发的方法
error:function(){
alert("上传失败");
}
});
});
文件或图片下载
控制层
@RequestMapping(value="/download")
publicStringdownloads(HttpServletResponseresponse,HttpServletRequestrequest)throwsException{
//要下载的图片地址
Stringpath=request.getServletContext().getRealPath("/upload");
StringfileName="基础语法.jpg";
//1、设置response响应头
response.reset();//设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8");//字符编码
response.setContentType("multipart/form-data");//二进制传输数据
//设置响应头
response.setHeader("Content-Disposition",
"attachment;fileName="+URLEncoder.encode(fileName,"UTF-8"));
Filefile=newFile(path,fileName);
//2、读取文件--输入流
InputStreaminput=newFileInputStream(file);
//3、写出文件--输出流
OutputStreamout=response.getOutputStream();
byte[]buff=newbyte[1024];
intindex=0;
//4、执行写出操作
while((index=input.read(buff))!=-1){
out.write(buff,0,index);
out.flush();
}
out.close();
input.close();
returnnull;
}
HTML页面
点击下载
SpringBoot文件或图片上传与下载就可以了
到此这篇关于SpringBoot文件或图片上传与下载功能的实现的文章就介绍到这了,更多相关SpringBoot文件上传与下载内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。