Java上传图片或者视频代码
时间: 2023-05-28 09:03:24 浏览: 130
以下是Java上传图片或视频的示例代码:
上传图片:
```
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
public class ImageUploadService {
public void uploadImage(MultipartFile file) throws IOException {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的扩展名
String extension = fileName.substring(fileName.lastIndexOf("."));
// 生成新的文件名
String newFileName = System.currentTimeMillis() + extension;
// 获取文件的保存路径
String filePath = "D:\\upload\\images\\" + newFileName;
// 创建文件对象
File dest = new File(filePath);
// 判断路径是否存在,如果不存在则创建路径
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
// 将文件保存到服务器
file.transferTo(dest);
}
}
```
上传视频:
```
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
public class VideoUploadService {
public void uploadVideo(MultipartFile file) throws IOException {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的扩展名
String extension = fileName.substring(fileName.lastIndexOf("."));
// 生成新的文件名
String newFileName = System.currentTimeMillis() + extension;
// 获取文件的保存路径
String filePath = "D:\\upload\\videos\\" + newFileName;
// 创建文件对象
File dest = new File(filePath);
// 判断路径是否存在,如果不存在则创建路径
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
// 将文件保存到服务器
file.transferTo(dest);
}
}
```
注意:以上代码中的路径为示例路径,上传文件的路径需根据实际情况进行修改。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)