Requirements : Upload files to a remote server and provide download functions.
Solution: Use Apache2, Tomcat or FTP to build a file server.
There are many online tutorials on the deployment of Apache2, Tomcat, and FTP. I have used all three, mainly divided into two methods:
For example, ftp can directly upload and download the java project after connecting with it. There are many tutorials on the Internet for this method;
If you use Apache2 and Tomcat, you can’t upload it directly. You can only deploy a project on the server to complete the operation of the server file. The following is how to achieve this. After setting up a service in Apache2, Tomcat, and FTP, create a directory to save files. I used apache2, so I put the files in /var/www/ and created a file folder. Then you need two springboot projects, one as the server and the other as the client.
Client:
Front page:
<input id="cert" type="file" onchange="submit()" />
function submit() {
var formData = new FormData();
formData.append('file', $("#cert")[0].files[0]); //生成一对表单属性
console.log(formData)
$.ajax({
type: "POST", //因为是传输文件,所以必须是post
url: '/upload', //对应的后台处理类的地址
data: formData,
processData: false,
contentType: false,
success: function(data) {
}
});
}
Client background interface:
@ApiOperation(value = "上传图片接口")
@PostMapping(value = "/upload")
public String upload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "失败";
}
JSONObject postData = new JSONObject();
String fileName = file.getOriginalFilename();//上传的文件名
String suffixName = fileName.substring(fileName.lastIndexOf("."));//获取后缀
fileName = UUID.randomUUID() + suffixName;//生成唯一文件名
try {
byte[] fileBytes = file.getBytes();//转换为byte数组
postData.put("fileName",fileName);
postData.put("data",fileBytes);
RestTemplate client = new RestTemplate();
//FilePath是你服务端的项目接口路径
JSONObject json = client.postForEntity(FilePath, postData, JSONObject.class).getBody();
logger.info("上传成功");
return json.get("data");//返回文件下载地址
} catch (IOException e) {
logger.error(e.toString(), e);
}
logger.info("上传失败");
return "失败";
}
The download address of the file is returned after the upload is successful.
Server interface:
@RestController
@RequestMapping(value = "upload")
@Slf4j
public class API {
/**
* 访问服务器文件路径端口
*/
@Value(value="${filePath}")
private String imgPath;
/**
* 服务器保存文件路径
*/
@Value(value="${uploadHost}")
private String uploadHost;
/**
* 项目host路径
*/
@ApiOperation(value = "上传图片接口", notes = "")
@PostMapping(value = "/upImg")
public JSONObject upImg(@RequestBody String json) {
JSONObject jsonObject =new JSONObject();
byte[] bfile = JSONObject.parseObject(json).getBytes("data");
String fileName =JSONObject.parseObject(json).getString("fileName");
byte2File(bfile,uploadHost,fileName);
if (json.isEmpty()) {
return null;
}
try {
log.info("上传成功");
jsonObject.put("data",imgPath+fileName);
return jsonObject;
} catch (Exception e) {
log.info("上传失败");
jsonObject.put("message",e.toString());
}
return jsonObject;
}
//byte数组转file文件方法
public static void byte2File(byte[] bfile,String filePath,String fileName){
BufferedOutputStream bos=null;
FileOutputStream fos=null;
File file=null;
try{
File dir=new File(filePath);
if(!dir.exists() && !dir.isDirectory()){//判断文件目录是否存在
dir.mkdirs();
}
file=new File(filePath+fileName);
fos=new FileOutputStream(file);
bos=new BufferedOutputStream(fos);
bos.write(bfile);
}
catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
finally{
try{
if(bos != null){
bos.close();
}
if(fos != null){
fos.close();
}
}
catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
Server configuration file application.yml
server:
port: 8099
#访问服务器文件路径端口
filePath: http://你的IP:88/
#服务器保存文件路径
uploadHost: /var/www/file/