Maven依赖:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.3</version> </dependency>
<dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.5</version> </dependency>
|
一、本地
Java实现把图片上传到本地
配置文件
path.properties配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| data.store.local=/home/***/data
articlePath=article
illustrationPath=illustration
userPath=user
photoPath=photo
data.store.local.suffix=*
|
调用
ArticleController.java的内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @RequestMapping("/api/rest/nanshengbbs/v3.0/article") @Controller public class ArticleController { @Autowired FileUploadUtil fileUploadUtil; @Autowired PathUtil pathUtil; @PostMapping("/setArticle") @ResponseBody public ReturnT<?> setArticle(@RequestParam(value = "picture", required = false)) { try { String newFileName = fileUploadUtil.save(file, pathUtil.getArticlePath());
return ReturnT.success("发布文章成功"); } catch (Exception e) { logger.error("发布文章失败"); return ReturnT.fail("发布文章失败"); } } }
|
工具类
FileUploadUtil.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream;
@PropertySource({"classpath:path.properties"}) @Component public class FileUploadUtil { private static Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
@Value("${data.store.local}") private String rootPath; @Value("${data.store.local.suffix}") private String suffix;
private List<String> suffixList = null;
@PostConstruct private void init(){ if (StringUtil.isNotEmpty(suffix)){ suffixList = Stream.of(suffix.split("(, *)+")) .map(s -> s.trim().toLowerCase()).collect(Collectors.toList()); } }
public String save(MultipartFile file, String folder){ String orginalName = file.getOriginalFilename(); if (checkFile(orginalName)){ String fileName = generateFileName(orginalName); String targetPath = generateStorePath(folder, fileName); String path = storeData(targetPath, file); logger.info("已保存文件:" + path);
return path; } else { logger.info("不支持上传该类型的文件:" + orginalName); return null; } }
public static void del(String fulPath){ File targetFile = new File(fulPath); targetFile.delete(); }
public String generateFileName(String orginalName){ return DateUtil.getNowDate() + "_" + orginalName; }
public String generateStorePath(String folder, String fileName){ return Paths.get(rootPath, folder, fileName).toString(); }
public String storeData(String path, MultipartFile file){ File stored = new File(path); try (InputStream in = file.getInputStream();){ FileUtils.copyInputStreamToFile(in, stored); return stored.getCanonicalPath(); } catch (IOException e) { logger.error(e.getMessage(), e); return null; } }
public boolean checkFile(String fileName){ if (suffixList.size() == 1 && suffixList.get(0).equals("*")){ return true; } String ext = FilenameUtils.getExtension(fileName); return suffixList.contains(ext.toLowerCase()); } }
|
StringUtil.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class StringUtil {
public static boolean isEmpty(String data){ return data == null || "".equals(data); }
public static boolean isNotEmpty(String data){ return !isEmpty(data); } }
|
PathUtil.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component;
@PropertySource({"classpath:path.properties"}) @Component public class PathUtil { @Value("${articlePath}") private String articlePath; @Value("${illustrationPath}") private String illustrationPath; @Value("${userPath}") private String userPath; @Value("${photoPath}") private String photoPath;
public String getArticlePath() { return articlePath; }
public void setArticlePath(String articlePath) { this.articlePath = articlePath; }
public String getIllustrationPath() { return illustrationPath; }
public void setIllustrationPath(String illustrationPath) { this.illustrationPath = illustrationPath; }
public String getUserPath() { return userPath; }
public void setUserPath(String userPath) { this.userPath = userPath; }
public String getPhotoPath() { return photoPath; }
public void setPhotoPath(String photoPath) { this.photoPath = photoPath; } }
|
二、图片服务器
Java实现把图片上传到图片服务器(nginx+vsftp)
nginx搭建参考:搭建http服务器-nginx
vsftp搭建参考:Vsftp安装与配置
配置文件
path.properties配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| ftp.address=*.*.*.* ftp.port=21 ftp.username=ftpuser ftp.password=******
data.store.local=/home/ftpuser/***/data
image.base.url=http://*.nanshengbbs.top/***/data
articlePath=article
illustrationPath=illustration
userPath=user
photoPath=photo
|
调用
ArticleController.java的内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| @RequestMapping("/api/rest/nanshengbbs/v3.0/article") @Controller public class ArticleController { @Autowired FtpUtil ftpUtil; @Autowired PathUtil pathUtil; @PostMapping("/setArticle") @ResponseBody public ReturnT<?> setArticle(@RequestParam(value = "picture", required = false)) { try { String fileName = UUIDUtil.getRandomUUID() + file.getOriginalFilename() .substring(file.getOriginalFilename().lastIndexOf(".")); String newFileName = ftpUtil.uploadFile(pathUtil.getArticlePath(), fileName, file.getInputStream());
return ReturnT.success("发布文章成功"); } catch (Exception e) { logger.error("发布文章失败"); return ReturnT.fail("发布文章失败"); } } }
|
工具类
FtpUtil.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths;
@PropertySource({"classpath:path.properties"}) @Component public class FtpUtil { @Value("${ftp.address}") private String host; @Value("${ftp.port}") private int port; @Value("${ftp.username}") private String username; @Value("${ftp.password}") private String password; @Value("${data.store.local}") private String basePath; @Value("${image.base.url}") private String imageUrl;
public String uploadFile(String filePath, String fileName, InputStream input) { String result = null; FTPClient ftp = new FTPClient(); try { ftp.connect(host, port); ftp.login(username, password); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return result; }
if (!ftp.changeWorkingDirectory(Paths.get(basePath, filePath).toString())) { String[] dirs = filePath.split("/"); String tempPath = basePath; for (String dir : dirs) { if (null == dir || "".equals(dir)) continue; tempPath += "/" + dir; if (!ftp.changeWorkingDirectory(tempPath)) { if (!ftp.makeDirectory(tempPath)) { return result; } else { ftp.changeWorkingDirectory(tempPath); } } } }
ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); fileName = CommonUtil.getRemoveChinese(fileName); if (!ftp.storeFile(fileName, input)) { return result; } result = imageUrl + "/" + filePath + "/" + fileName; } catch (IOException e) { e.printStackTrace(); } finally { try { input.close(); ftp.logout(); if (ftp.isConnected()) { ftp.disconnect(); } } catch (Exception e) {} } System.out.println(result); return result; } }
|
三、第三方
Java实现把图片上传到七牛云对象存储
七牛官网:https://developer.qiniu.com/
对象存储Java SDK:https://developer.qiniu.com/kodo/sdk/1239/java
配置文件
76.properties配置如下:
1 2 3
| AccessKey=************************************** SecretKey==**************************************
|
path.properties配置如下:
1 2
| 76.image.domain=http://*.nanshengbbs.top
|
调用
ArticleController.java的内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| @RequestMapping("/api/rest/nanshengbbs/v3.0/article") @Controller public class ArticleController { @Autowired FtpUtil ftpUtil; @Autowired PathUtil pathUtil; @PostMapping("/setArticle") @ResponseBody public ReturnT<?> setArticle(@RequestParam(value = "picture", required = false)) { try { String fileName = UUIDUtil.getRandomUUID() + file.getOriginalFilename(); String newFileName = QiniuUtil.upload(file.getInputStream(), fileName);
return ReturnT.success("发布文章成功"); } catch (Exception e) { logger.error("发布文章失败"); return ReturnT.fail("发布文章失败"); } } }
|
工具类
QiniuUtil.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| import com.google.gson.Gson; import com.qiniu.http.Response; import com.qiniu.storage.Configuration; import com.qiniu.storage.Region; import com.qiniu.storage.UploadManager; import com.qiniu.storage.model.DefaultPutRet; import com.qiniu.util.Auth;
import java.io.IOException; import java.io.InputStream;
public class QiniuUtil { private static final String ACCESS_KEY = PropertyUtil.getProperties76().getProperty("AccessKey"); private static final String SECRET_KEY = PropertyUtil.getProperties76().getProperty("SecretKey"); private static final String bucket = "nanshengbbs"; private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); private static final String upToken = auth.uploadToken(bucket); private static final Configuration cfg = new Configuration(Region.huanan()); private static final UploadManager uploadManager = new UploadManager(cfg);
public static String upload(String localFilePath, String fileName) throws Exception { Response res = uploadManager.put(localFilePath, fileName, upToken); DefaultPutRet putRet = new Gson() .fromJson(res.bodyString(), DefaultPutRet.class); return putRet.key; }
public static String upload(byte[] uploadBytes, String fileName) throws Exception { Response res = uploadManager.put(uploadBytes, fileName, upToken); DefaultPutRet putRet = new Gson() .fromJson(res.bodyString(), DefaultPutRet.class); return putRet.key; }
public static String upload(InputStream inputStream, String fileName) throws Exception { Response res = uploadManager.put(inputStream, fileName, upToken, null, null); DefaultPutRet putRet = new Gson() .fromJson(res.bodyString(), DefaultPutRet.class); return putRet.key; } }
|