一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java 上传文件和下载文件 工具类

时间:2022-06-29 02:35:03 编辑:袖梨 来源:一聚教程网

上传下载类如下

 

 代码如下 复制代码

public static void downloadFile(String fileName, String downloadName, HttpServletResponse response){
try {
response.setContentType("octets/stream");
response.addHeader("Content-Type", "text/html; charset=utf-8");
String downLoadName = new String(downloadName.getBytes("gbk"), "iso8859-1");
response.addHeader("Content-Disposition", "attachment;filename=" + downLoadName);

FileInputStream fileInputStream = new FileInputStream(fileName);
OutputStream out = response.getOutputStream();
int i = 0;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
 
/**
 * 上传文件
 *
 * @param file
 *            文件
 * @param radomfileName
 *            保存文件名
 * @param materialFilePath
 *            保存路径
 * @return
 */
public static boolean fileUpload(MultipartFile file, String radomfileName,
String materialFilePath) {
boolean flag = true;
File baseFile = new File(materialFilePath);
File trainFile = new File(baseFile, radomfileName);
if (!baseFile.exists()) {
baseFile.mkdirs();
}
try {
file.transferTo(trainFile);
} catch (IllegalStateException e) {
flag = false;
} catch (IOException e) {
flag = false;
}// 保存文件
return flag;
}

热门栏目