/**
*上传
*/
public static String uploadFile(MultipartFile file) {
String fileName = file.getOriginalFilename();
String name = fileName.substring(0, fileName.lastIndexOf("."));
String extension = fileName.substring(fileName.lastIndexOf("."));
String filePath = System.getProperty("user.dir") + "\\whnbgd\\";
File targetFile = new File(filePath);
// 第一步:判断文件是否为空
if (file.isEmpty())
return fileName + "文件为空";
// 第二步:判断目录是否存在 不存在:创建目录
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 第三步:通过输出流将文件写入硬盘文件夹并关闭流
BufferedOutputStream stream = null;
// 防止文件覆盖
String nowTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
try {
stream = new BufferedOutputStream(new FileOutputStream(filePath + name + nowTime + extension));
stream.write(file.getBytes());
stream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (stream != null)
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return fileName + "上传成功";
}
/**
*下载
*
*/
public static void downloadNet(String urlStr, String wjcfdz, HttpServletResponse response) throws MalformedURLException {
// 下载网络文件
int bytesum = 0;
int byteread = 0;
URL url = new URL(urlStr);
try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream(wjcfdz);
byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Java文件上传下载方法 :
最新推荐文章于 2025-10-21 09:11:44 发布
此篇博客介绍了如何使用Java进行文件上传,包括验证文件、创建目录和写入硬盘,以及下载网络文件的方法。重点展示了处理MultipartFile和URL的实用技巧。
683

被折叠的 条评论
为什么被折叠?



