文件上传
一、上传文件到本地
package com.ruoyi.system.knowledgebase;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.SzKnowledge;
import com.ruoyi.system.service.ISzKnowledgeService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@RestController
@RequestMapping("/KnowledgeUpload")
public class KnowledgeUpload {
@Autowired
private ISzKnowledgeService szKnowledgeService;
@Anonymous
@PostMapping("/upload")
public AjaxResult uploadToLocal(@Param("file") MultipartFile file, @Param("userId")String userId){
// 获取文件原本的名字
String originName = file.getOriginalFilename();
// 判断文件是否是pdf文件
Set<String> set = new HashSet<>();
set.add(".docx");
set.add(".doc");
set.add(".xls");
set.add(".xlsx");
set.add(".pdf");
// 取出文件的后缀
int count = 0;
for(int i = 0; i < originName.length(); i++){
if(originName.charAt(i) == '.'){
count = i;
break;
}
}
String endName = originName.substring(count); //取出文件类型
if(!set.contains(endName)){
return AjaxResult.error("上传的文件类型错误");
}
// 创建保存路径
//日期格式
// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// String format = sdf.format(new Date());
String savePath = "D:\\Apache24\\htdocs\\knowledge_user";
// String savePath = "/var/www/html/upload_file";
// 保存文件的文件夹
File folder = new File(savePath);
// 判断路径是否存在,不存在则自动创建
if(!folder.exists()){
folder.mkdirs();
}
//截取后缀
final String suffix = originName.substring(originName.lastIndexOf("."));
//为文件命名
final String finalName = UUID.randomUUID() + suffix;
//String saveName = originName;
System.out.println("finalName = " + finalName);
try {
// 保存文件到磁盘
file.transferTo(targetFile);
String saveAi = "http://xxx.xxxx.x.x:9012/knowledge/" + finalName;
return AjaxResult.success("上传成功", saveAi);
} catch (IOException e){
return AjaxResult.error("上传失败");
}
}
}
二、上传文件到远程服务器(SFTP)
<!--sftp文件上传-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
package com.ruoyi.system.knowledgebase;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.*;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
public class FtpUtils {
/**
* 利用JSch包实现SFTP上传文件
* @param bytes 文件字节流
* @param fileName 文件名
* @throws Exception
*/
public static void sshSftp(byte[] bytes,String fileName) throws Exception{
//指定的服务器地址
String ip = "43.XXX.XXX.XX";
//用户名
String user = "XXXXX";
//密码
String password = "XXXXX";
//服务器端口 默认22
int port = 22;
//上传文件到指定服务器的指定目录 自行修改
String path = "/root";
Session session = null;
Channel channel = null;
JSch jsch = new JSch();
if(port <=0){
//连接服务器,采用默认端口
session = jsch.getSession(user, ip);
}else{
//采用指定的端口连接服务器
session = jsch.getSession(user, ip ,port);
}
//如果服务器连接不上,则抛出异常
if (session == null) {
throw new Exception("session is null");
}
//设置登陆主机的密码
session.setPassword(password);//设置密码
//设置第一次登陆的时候提示,可选值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
//设置登陆超时时间
session.connect(30000);
OutputStream outstream = null;
try {
//创建sftp通信通道
channel = (Channel) session.openChannel("sftp");
channel.connect(1000);
ChannelSftp sftp = (ChannelSftp) channel;
//进入服务器指定的文件夹
sftp.cd(path);
//列出服务器指定的文件列表
// Vector v = sftp.ls("*");
// for(int i=0;i<v.size();i++){
// System.out.println(v.get(i));
// }
//以下代码实现从本地上传一个文件到服务器,如果要实现下载,对换以下流就可以了
outstream = sftp.put(fileName);
outstream.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
//关流操作
if(outstream != null){
outstream.flush();
outstream.close();
}
if(session != null){
session.disconnect();
}
if(channel != null){
channel.disconnect();
}
}
}
public static boolean isAllowedFileType(String fileName) {
// 允许上传的文件类型
Set<String> allowedTypes = new HashSet<>();
allowedTypes.add(".doc");
allowedTypes.add(".docx");
allowedTypes.add(".pdf");
allowedTypes.add(".xls");
allowedTypes.add(".xlsx");
// 获取文件的后缀
int count = fileName.lastIndexOf(".");
String endName = fileName.substring(count).toLowerCase();
return allowedTypes.contains(endName);
}
}
package com.ruoyi.system.knowledgebase;
import com.ruoyi.system.service.ISzKnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;
import static com.ruoyi.system.knowledgebase.FtpUtils.isAllowedFileType;
@RestController
@RequestMapping("/KnowledgeUpload")
public class FileUpload
{
@Autowired
private ISzKnowledgeService szKnowledgeService;
@RequestMapping("/file")
public void upload(MultipartFile file){
String fileName = file.getOriginalFilename();
//截取后缀
final String suffix = fileName.substring(fileName.lastIndexOf("."));
//为文件命名
final String finalName = UUID.randomUUID() + suffix;
if (!isAllowedFileType(fileName)) {
System.out.println("上传的文件类型错误");
return;
}
try {
byte[] bytes = file.getBytes();
FtpUtils.sshSftp(bytes,finalName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
APIfox接口测试
三、文件上传到云存储服务器
-
使用七牛云进行文件上传http://t.csdn.cn/qONcF
-
使用阿里云oss进行文件上传
阿里云oss对象存储:http://t.csdn.cn/dYmsq
//采集并上传音频到oss服务器 @Anonymous @PostMapping("/uploadAudio") public String uploadAudio(@RequestParam("audioFile") MultipartFile audioFile, @RequestParam("voiceName") String voiceName, @RequestParam("audioId") String audioId) { String response = UploadController.uploadAudio(audioFile,voiceName,audioId); return response; }
public class AliYunConstants { public static final String ACCESSKEY_ID = "xxxxxxxxxxxx"; public static final String ACCESSKEY_SECRET = "xxxxxxxxxxxxx"; }
package com.ruoyi.system.soundcloing; import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.ruoyi.common.annotation.Anonymous; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.system.controller.AliYunConstants; import org.springframework.web.bind.annotation.PostMapping; 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 java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @RestController @RequestMapping("/upload") public class UploadController { // 阿里云 OSS 的 Endpoint private static final String OSS_ENDPOINT = "http://oss-cn-beijing.aliyuncs.com"; private static final String OSS_ENDPOINT2 = "http://oss-cn-hangzhou.aliyuncs.com"; //阿里云存储地址1 private static final String OSS_AUDIOURL = "https://xxxx.oss-cn-beijing.aliyuncs.com/"; private static final String OSS_AUDIOURL2 = "https://xxxx.oss-cn-hangzhou.aliyuncs.com/"; // 阿里云 OSS 的 Bucket 名称 private static final String OSS_BUCKET_NAME = "xxxx"; private static final String OSS_BUCKET_NAME2 = "xxxxx"; //文件上传测试接口 @Anonymous @PostMapping("/audio") public AjaxResult upload(@RequestParam("audioFile") MultipartFile audioFile, @RequestParam("voiceName") String voiceName, @RequestParam("audioId") String audioId){ // 初始化 OSS 客户端 OSS ossClient = new OSSClientBuilder().build(OSS_ENDPOINT, AliYunConstants.ACCESSKEY_ID, AliYunConstants.ACCESSKEY_SECRET); try { // 上传的 Object 完整路径,例如:soundcloning/voiceName/audioId.png String objectName = "soundcloning/" + voiceName + "/" + audioId + ".wav"; // 将录音文件上传到 OSS ossClient.putObject(OSS_BUCKET_NAME, objectName, new ByteArrayInputStream(audioFile.getBytes())); String result = OSS_AUDIOURL+ objectName; return AjaxResult.success("音频文件上传成功",result); // return "音频文件上传成功,Object 完整路径为:"+ OSS_ENDPOINT+ objectName; } catch (OSSException oe) { // 处理 OSS 异常 return AjaxResult.error("上传失败,OSS 异常", oe.getMessage()); // return "上传失败,OSS 异常:" + oe.getMessage(); } catch (ClientException ce) { // 处理 OSS Client 异常 return AjaxResult.error("上传失败,OSS 异常", ce.getMessage()); // return "上传失败,OSS Client 异常:" + ce.getMessage(); } catch (IOException e) { // 处理文件读取异常 return AjaxResult.error("上传失败,OSS 异常",e.getMessage()); // return "上传失败,文件读取异常:" + e.getMessage(); } finally { // 关闭 OSS 客户端 if (ossClient != null) { ossClient.shutdown(); } } } public static String uploadAudio( MultipartFile audioFile, String voiceName, String audioId){ // 初始化 OSS 客户端 OSS ossClient = new OSSClientBuilder().build(OSS_ENDPOINT, AliYunConstants.ACCESSKEY_ID, AliYunConstants.ACCESSKEY_SECRET); try { // 上传的 Object 完整路径,例如:soundcloning/voiceName/audioId.png String objectName = "soundcloning/" + voiceName + "/" + audioId + ".wav"; // String objectName = "soundcloning/" + voiceName + "/" + audioId; // File file = AudioProcessing.uploadAudioAsFile(audioFile); // 将MultipartFile转换为File // File newFile = new File(audioFile.getOriginalFilename()); // FileUtils.copyInputStreamToFile(audioFile.getInputStream(), newFile); // 将录音文件上传到 OSS ossClient.putObject(OSS_BUCKET_NAME, objectName, new ByteArrayInputStream(audioFile.getBytes())); // ossClient.putObject(OSS_BUCKET_NAME, objectName,new FileInputStream(newFile)); // ossClient.putObject(OSS_BUCKET_NAME, objectName,new FileInputStream(file)); String result = OSS_AUDIOURL+ objectName; return result; } catch (OSSException oe) { // 处理 OSS 异常 return "上传失败,OSS 异常:" + oe.getMessage(); } catch (ClientException ce) { // 处理 OSS Client 异常 return "上传失败,OSS Client 异常:" + ce.getMessage(); } catch (IOException e) { // 处理文件读取异常 return "上传失败,文件读取异常:" + e.getMessage(); } finally { // 关闭 OSS 客户端 if (ossClient != null) { ossClient.shutdown(); } } } }