文件上传是Web中常见的功能,选择性也很多,比如将文件上传到oss等类似的文件服务器上,这种方式成本比较高。文件的上传和显示操作比较简单。另外就是在文件上传到项目路径的静态资源文件夹resources/下。还可以上传到mongodb中。
这次使用Springboot提供了的静态资源的映射方式
你可以添加一个外部文件夹并将其作为一个静态资源文件夹的映射,也就是说添加这个映射后你可以在项目中像访问静态资源文件夹一样来访问外部的文件夹。
具体代码:
在项目中新建一个类,创建映射的静态资源请求路径。
package com.herbert.upload.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Created by Herbert on 2020/4/8.
* zhaixingzu@163.com
*/
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("file:F:/img/");
}
}
"/img/**" 就是映射的静态资源请求路径
下来测试下静态资源是否配置成功:
在F盘符下建立文件夹img 。然后放一张图片为code.png 通过映射的静态资源请求路径访问:
启动项目
访问http://127.0.0.1:8080/img/code.png
上传文件代码:
package com.herbert.upload.controller;
import com.alibaba.fastjson.JSON;
import com.wwj.imageupload.util.FileUtils;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
@RestController
public class ImageUploadController {
@RequestMapping("/imageUpload")
public Map imageUpload(@RequestParam("fileName") MultipartFile file){
String result_msg="";//上传结果信息
Map<String,Object> root=new HashMap<String, Object>();
if (file.getSize() / 1000 > 100){
result_msg="图片大小不能超过100KB";
}else{
//判断上传文件格式
String fileType = file.getContentType();
if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpeg")) {
// 要上传的目标文件存放的绝对路径
//用src为保存绝对路径不能改名只能用原名,不用原名会导致ajax上传图片后在前端显示时出现404错误-->原因未知
// String localPath="F:\\IDEAProject\\imageupload\\src\\main\\resources\\static\\img";
final String localPath="F:\\img";
//上传后保存的文件名(需要防止图片重名导致的文件覆盖)
//获取文件名
String fileName = file.getOriginalFilename();
//获取文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//重新生成文件名
fileName = UUID.randomUUID()+suffixName;
if (FileUtils.upload(file, localPath, fileName)) {
//文件存放的相对路径(一般存放在数据库用于img标签的src)
String relativePath="img/"+fileName;
root.put("relativePath",relativePath);//前端根据是否存在该字段来判断上传是否成功
result_msg="图片上传成功";
}
else{
result_msg="图片上传失败";
}
}
else{
result_msg="图片格式不正确";
}
}
root.put("result_msg",result_msg);
String root_json=JSON.toJSONString(root);
System.out.println(root_json);
return root;
}
}
下载代码:
@RequestMapping("/download")
public void downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
String filename="code.png";
String filePath = "F:\\img" ;
File file = new File(filePath + "/" + filename);
if(file.exists()){
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename,"utf8"));
byte[] buffer = new byte[1024];
//输出流
OutputStream os = null;
try(FileInputStream fis= new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);) {
os = response.getOutputStream();
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试上传,下载功能:
到此:图片上传,显示功能已经完成。
下来测试下载功能
源码下载:https://download.csdn.net/download/weixin_41986096/12315498