跨域上传和读取文件
前言
需求
在Liunx服务器上建立了自己存放图片的文件夹,想通过Springboot进行图片的上传或读取
效果
上传:
读取:
以下两种方法都可以
一、若文件夹创建在自定义的位置
1.进入宝塔面板修改tomcat的server.xml文件
加上下面这句
<Context docBase ="/home/springbootVue/files" path ="/home/springbootVue/files" debug ="0" reloadable ="true"/>
docBase代表文件路径,path是浏览器访问时的路径。
添加之后重启tomcat
就可以通过浏览器访问到这个文件里边的内容了
2.对创建的files文件设置可读写权限
chmod 777 '文件名'
3.写Springboot后端接口
1)导入maven依赖
<!--跨域上传文件-->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
2)在 application.yaml 文件中设置最大传输文件容量
spring:
servlet:
multipart:
enabled: true
max-file-size: 30MB
max-request-size: 30MB
3)写controller层
@RestController
public class FileController {
@PostMapping("/upload")
public String Upload(MultipartFile file){
String path = "http://主机号:8080/home/springbootVue/files/";
//以当前时间命名图片的名字(也可使用其他方法命名 比如UUID)
String originalFilename = file.getOriginalFilename();
//新文件名前缀
String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//新文件名后缀
String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String newFileName=fileNamePrefix+fileNameSuffix;
try{
//使用Jersey客户端上传文件
Client client = Client.create();
WebResource webResource = client.resource(path + newFileName);
webResource.put(file.getBytes());
System.out.println("上传成功");
System.out.println("图片路径==》"+path+newFileName);
}catch(Exception e){
System.out.println("上传失败");
}
return "";
}
}
该段代码部分参考博主「我认不到你」
原文链接:https://blog.csdn.net/qq_57581439/article/details/124892306
4.测试接口
使用Postman测试
上传成功
进入浏览器中也可以看到刚才上传的图片文件
二、若文件夹创建在tomcat目录的webapps中
若自己创建的文件夹在tomcat目录的webapps中,如下
方法与上述类似
不同之处: docBase直接写文件夹文字即可(注意:没有/)
可读写配置在web.xml里边配置
> <init-param>
> <param-name>listings</param-name>
> <param-value>true</param-value>
> </init-param>
> <init-param>
> <param-name>readonly</param-name>
> <param-value>false</param-value>
> </init-param>