- 引言
项目中使用了spring boot框架,要开发新的上传下载功能,总结一下自己的经验和工作。方便大家引用和少踩坑!(JDK采用1.8) - 1 引入maven依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
- 2 controller层主要使用MultipartFile这个spring框架自带的文件上传工具类,前端只需要使用from表单,然后使用ajax提交即可
import com.supermap.application.common.ReturnObject;
import com.supermap.application.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
@Controller
@RequestMapping(value = "/file/upload")
public class FileUploadController {
@Autowired
FileUploadService fileUploadService;
@PostMapping("/server")
@ResponseBody
public ReturnObject uploadFileToServer(@RequestParam("file") MultipartFile file,
String fileName,String serverUploadAddress) {
String newName = fileUploadService.getWholeName(file,fileName);
return fileUploadService.uploadFile(file,newName,serverUploadAddress);
}
@GetMapping("/get/files")
@ResponseBody
public ReturnObject getAllFileDirectory(String filePath) {
return fileUploadService.getAllFileDirectory(filePath);
}
@GetMapping(value = "/download")
@ResponseBody
public ReturnObject Download(HttpServletResponse response,String filePath,String fileName) {
return fileUploadService.download(response,filePath,fileName);
}
}
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import com.supermap.application.common.ReturnObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@Service
public class FileUploadService {
@Value("${server.upload.address}")
private String serverUploadAddress;
public String getWholeName(MultipartFile file,String fileName){
String afterName = file.getOriginalFilename();
String suffix = getSuffixName(afterName);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(fileName).append(suffix);
String newName = stringBuffer.toString();
return newName;
}
public String getSuffixName(String afterName){
return afterName.substring(afterName.lastIndexOf("."));
}
public ReturnObject uploadFile(MultipartFile file,String fileName,String serverPath){
if (!file.isEmpty()) {
try {
File serverFileDirectory = new File(serverPath);
if (!serverFileDirectory.exists()) {
serverFileDirectory.mkdir();
}
file.transferTo(new File(serverPath + fileName));
}catch (IOException e){
e.printStackTrace();
}
return new ReturnObject(true,"请求成功!","文件上传成功!");
} else {
return new ReturnObject("上传文件为空");
}
}
public ReturnObject getAllFileDirectory(String filePath){
if (filePath.isEmpty()) {
filePath = serverUploadAddress;
}
Map<String,String> map = new HashMap<>();
File directory = new File(filePath);
Collection<File> files = getTemplateDirectoryFiles(directory);
if (files.size() < 1) {
return new ReturnObject("未上传任何文件");
}
files.forEach(t -> {
if (!t.isDirectory()) {
map.put(t.getName(),t.getAbsolutePath());
}
});
return new ReturnObject(map);
}
public Collection<File> getTemplateDirectoryFiles(File directory) {
return FileUtils.listFilesAndDirs(directory, TrueFileFilter.INSTANCE, DirectoryFileFilter.INSTANCE);
}
public ReturnObject download(HttpServletResponse res,String filepath,String fileName) {
res.setHeader("content-type", "application/octet-stream");
res.setContentType("application/octet-stream");
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
os = res.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(new File(filepath + fileName)));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
return new ReturnObject("系统找不到指定文件!");
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new ReturnObject(true,"请求成功!","下载文件成功!");
}
}
}
- 最后为大家奉上我自己写的统一返回值对象类ReturnObject
maven依赖net.json
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
import net.sf.json.JSONObject;
public class ReturnObject<T> {
private boolean status;
private String message;
private T data;
public ReturnObject() {
this.status = false;
this.message = "请求错误!";
this.data = null;
}
public ReturnObject(boolean status, String message, T data) {
this.status = status;
this.message = message;
this.data = data;
}
public ReturnObject(T data) {
this.status = true;
this.message = "请求成功!";
this.data = data;
}
public ReturnObject(String message) {
this.status = false;
this.message = message;
this.data = null;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public JSONObject toJson(ReturnObject returnObject){
return JSONObject.fromObject(returnObject);
}
public synchronized ReturnObject<T> append(Boolean boo){
this.setStatus(boo);
return this;
}
public synchronized ReturnObject<T> append(String str){
this.setMessage(str);
return this;
}
public synchronized ReturnObject<T> append(T t){
this.setData(t);
return this;
}
}