从本地上传的到服务器
/**
* 上传文件到指定目录
* @param filePath 服务器路径
* @param file 本地文件
* @return
*/
public static int uploadFile(String filePath,MultipartFile file){
File desFile = new File(filePath);
if(!desFile.getParentFile().exists()){
desFile.getParentFile().mkdirs();
}
try {
file.transferTo(desFile);
} catch (IllegalStateException | IOException e) {
logger.info("子文件上传失败!");
e.printStackTrace();
return 1;
}
return 0;
}
从服务器下载到本地
/**
* 文件下载
* @param path 服务器上的文件路径
* @param response
* @return
*/
public static int downloadFile(String path, HttpServletResponse response) {
int result = 1;
InputStream is = null;
OutputStream os = null;
try {
File file = new File(path);
// 清空response
response.reset();
// 设置response的Header
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "utf-8"));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
is = new FileInputStream(file);
os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) > 0) {
os.write(b, 0, length);
}
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
result = 0;
} finally {
closeInputStream(is);
closeOutputStream(os);
}
return result;
}
下面是两个关流的方法
private static void closeInputStream(InputStream is) {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void closeOutputStream(OutputStream os) {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}