java实现文件的上传下载
public HashMap<String, Object> downloadFile( HttpServletResponse response ,Model model,HashMap<String, Object> errorMap,HttpServletRequest request) {
//待下载文件名
String fileName = (String) model.asMap().get("downloadName");// 文件中文显示乱码
String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
// win10 ie edge 浏览器 和其他系统的ie
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// fe
fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
}
//设置为格式的文件
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
byte[] buff = new byte[1024];
//创建缓冲输入流
BufferedInputStream bis = null;
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();//这个路径为待下载文件的路径
bis = new BufferedInputStream(new FileInputStream(new File((String) model.asMap().get("newpath"))));
int read = bis.read(buff);//通过while循环写入到指定了的文件夹中
while (read != -1) {////并不是每次都能读到1024个字节,用read作为每次读取数据的长度,否则会出现文件损坏的错误
outputStream.write(buff, 0, read);
outputStream.flush();
read = bis.read(buff);
}
} catch ( IOException e ) {
e.printStackTrace();
//出现异常返回给页面失败的信息
errorMap.put("errorMap", true);
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}return errorMap;
}
/**
*
* @param model
* @param uploadFile
* @param errorMap
* @return
*/
private HashMap<String, Object> uploadFiles(Model model, MultipartFile uploadFile,
HashMap<String, Object> errorMap) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
//path路径均为常量
String path = new StringBuilder()
.append(uploadTemporaryDirectory)
.append(File.separator)
.append(CommonConstants.STR_TAS_TASK)
.append(File.separator)
.append(CommonConstants.STR_TAS_TEMPORARY_UPLOAD)
.append(File.separator)
.toString();
inputStream = uploadFile.getInputStream();
String fileName = uploadFile.getOriginalFilename();
File targetFile = new File(path + fileName);
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
outputStream = new FileOutputStream(targetFile);
FileCopyUtils.copy(inputStream, outputStream);
} catch (IOException e) {
e.printStackTrace();
errorMap.put("errorMap", true);
return errorMap;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return errorMap;
}
本文地址:https://blog.csdn.net/li15974168626/article/details/107245433
下一篇: 一文解决关于建立时间和保持时间的困惑