java上传下载通用方法总结 之file.transferTo(targetFile)(二)
最近新捕获文件上传、下载、预览的方法。特地总结,方便调用。
先看公共类的公共方法:
package com.sinux.cc.fileuploadanddownload.newfileio;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileIOUtil {
private static String prefix;
static {
/**
*它 是项目所在地址:这里的上传下载预览,都是要全路径跟(一)中的方法不一样
*E:\2020-in-beijing\java8\mycodeinbeijing
**/
prefix = System.getProperty("user.dir");
}
//下载
public static ResponseEntity downloadFile(String path) {
path = prefix + path;
File f = new File(path);
System.out.println(f);
if (f.exists() && f.isFile()) {
String fileName = f.getName();
try {
String contentType = Files.probeContentType(Paths.get(path));
Resource resource = new UrlResource(Paths.get(path).toUri());
if (StringUtils.isEmpty(contentType)) {
contentType = "application/" + fileName.substring(fileName.lastIndexOf(".") + 1);
}
// fileName = getFileName(fileName);
ResponseEntity<Resource> body = ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).
header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" +
new String(fileName.getBytes("UTF-8"), "ISO8859-1")).
body(resource);
return body;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
//预览
public static ResponseEntity previewFile(String path) {
path = prefix + path;
if (!StringUtils.isEmpty(path)) {
File file = new File(path);
if (file.exists()) {
String fileName = file.getName();
try {
String contentType = Files.probeContentType(Paths.get(path));
Resource resource = new UrlResource(Paths.get(path).toUri());
if (StringUtils.isEmpty(contentType)) {
if(fileName.endsWith(".svg")){
contentType = "image/svg+xml";
}else{
contentType = "application/" + fileName.substring(fileName.lastIndexOf(".") + 1);
}
}
return ResponseEntity.ok().
contentType(MediaType.parseMediaType(contentType)).
header(HttpHeaders.CONTENT_DISPOSITION, "inline;filename" +
URLEncoder.encode(fileName, "UTF-8")).body(resource);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
//上传
public static String uploadFile(MultipartFile file, String uploadpath) {
if (file != null) {
String fileName = file.getOriginalFilename();
if (!StringUtils.isEmpty(fileName)) {
String folderpath = prefix + uploadpath;
File f = new File(folderpath);
if (!f.exists()) {
f.mkdirs();
}
File targetFile = new File(f, fileName);
if (targetFile.exists()) {
targetFile.delete();
}
try {
file.transferTo(targetFile);
} catch (IOException e) {
e.printStackTrace();
}
return uploadpath + fileName;
}
}
return null;
}
}
调用的地方:
package com.sinux.cc.fileuploadanddownload.controller;
import com.sinux.cc.fileuploadanddownload.FileDownload;
import com.sinux.cc.fileuploadanddownload.FileUpload;
import com.sinux.cc.fileuploadanddownload.newfileio.FileIOUtil;
import com.sinux.cc.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
@RestController
@Api(tags = "文件上传下载操作")
@RequestMapping("/fileoperate")
@Slf4j
public class FileOperateController {
/**
*在yml中配置的:
*fileiodir:
* upanddown: "/files/0715file/"
**/
@Value("${fileiodir.upanddown}")
private String uploadpath;
@GetMapping("/jnf")
@ApiOperation(value = "使用java.nio.file下载文件")
public ResponseEntity testResponseEntity(String path){
log.info("path==============="+path);
ResponseEntity<InputStreamResource> inputStreamResourceResponseEntity = null;
try {
inputStreamResourceResponseEntity =
FileIOUtil.downloadFile(path);
} catch (Exception e) {
e.printStackTrace();
}
return inputStreamResourceResponseEntity;
}
@PostMapping("/uploadfiles")
@ApiOperation(value = "上传文件")
public R uploadFiles(MultipartFile file){
String s = FileIOUtil.uploadFile(file,uploadpath);
return R.ok("").put("path",s);
}
@PostMapping("/preview")
@ApiOperation(value = "预览图片")
public ResponseEntity preView(String path){
ResponseEntity responseEntity = FileIOUtil.previewFile(path);
return responseEntity;
}
}