vue+SpringBoot实现文件上传
今天我们来学习使用Vue+SpringBoot来实现文件上传,其实今天的重点在于前端使用Vue获取文件,并传输到后台,至于后台上传文件则是通用的代码。
·
今天我们来学习使用Vue+SpringBoot来实现文件上传,其实今天的重点在于前端使用Vue获取文件,并传输到后台,至于后台上传文件则是通用的代码。
Vue获取文件
- upload.html
前端我们使用了Vue.js,其中使用axios来发送异步请求。
<div id="app">
<input type="file" @change="getFile($event)">
<input type="button" value="上传" @click="upload()">
</div>
</body>
<script>
const app = new Vue({
el: "#app",
data: {
formData: new FormData(),
},
methods: {
upload() {
axios.post("/upload/image",this.formData).then(resp => {
if (resp.status == 200) {
alert("success");
}
});
},
getFile(event) {
let file = event.target.files[0];
let fileName = file.name;
let index = fileName.lastIndexOf(".");
if (index != -1) {
let suffix = fileName.substr(index + 1).toLowerCase();
if (suffix == 'png' || suffix == 'jpg') {
this.formData.append("file",file);
}
}
}
}
})
</script>
后台项目依赖
<!--SpringBoot的启动器-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent>
<dependencies>
<!--SpringMVC的启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--用来处理文件上传的一个通用工具类-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!--lombox插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
文件上传相关配置
- application.yml
file:
upload:
path: G:\temp\images\ #文件上传目标路径
allowTypes: #文件上传允许的类型
- image/jpeg
- image/png
- image/jpg
- image/bmp
- UploadProperties.java
/**
* 图片上传的Java配置类,通过SpringBoot自动读取配置文件注入
*/
@Data
@Component
@ConfigurationProperties(prefix = "file.upload")
public class UploadProperties {
// 图片上传路径
private String path;
// 文件上传允许类型
private List<String> allowTypes;
}
/**
* 图片上传的Java配置类
*/
@Configuration
public class UploadConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 单个数据大小
factory.setMaxFileSize("10240KB");
/// 总上传数据大小
factory.setMaxRequestSize("102400KB");
return factory.createMultipartConfig();
}
}
文件上传后台代码
- controller层
@RestController
@RequestMapping("upload")
public class UploadController {
@Autowired
private UploadService uploadService;
@PostMapping("image")
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
return ResponseEntity.ok(uploadService.uploadImage(file));
}
}
- service层接口
public interface UploadService {
/**
* 上传图片
* @param file
* @return
* @throws Exception
*/
String uploadImage(MultipartFile file) throws Exception;
}
- service层实现
@Service
public class UploadServiceImpl implements UploadService {
@Autowired
private UploadProperties uploadProperties;
@Override
public String uploadImage(MultipartFile file) throws IOException {
if(!uploadProperties.getAllowTypes().contains(file.getContentType())){
throw new IOException("文件上传类型错误!");
}
String fileName = UploadUtils.generateFileName(file.getOriginalFilename());
file.transferTo(new File(uploadProperties.getPath()+fileName));
return fileName;
}
}
文件上传工具类
- IDUtils
public class IDUtils {
/**
* 唯一ID生成器,可以生成唯一ID
*
* @return 唯一ID
*/
public static String generateUniqueId() {
return UUID.randomUUID().toString() + System.currentTimeMillis();
}
}
- UploadUtils
public class UploadUtils {
/**
* 文件名称替换工具,将文件名称替换为随机名称
*
* @param oldName 上传文件名字
* @return 生成的新文件名
*/
public static String generateFileName(String oldName) {
String suffix = oldName.substring(oldName.lastIndexOf("."));
return IDUtils.generateUniqueId() + suffix;
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)