JAVA文件上传下载

一、文件上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class UploadUtil {

public boolean upload(String fileUploadPath, MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();//获取文件名
// String newfilename = UUID.randomUUID().toString();
// String fix=filename.substring(filename.lastIndexOf("."),filename.length());
//String newfile = newfilename+fix;
String filePath = fileUploadPath+filename;//文件保存的地址及名称

File files = new File(filePath);
//检查文件夹是否存在
if(!files.getParentFile().exists()){
files.getParentFile().mkdirs();//新建文件夹
}
file.transferTo(files);//写入文件
return true;
}
public boolean uploads(String fileUploadPath, MultipartFile[] file) throws IOException {

for(MultipartFile name : file){

if(!name.isEmpty()){
String filename = name.getOriginalFilename();//获取文件名
// String newfilename = UUID.randomUUID().toString();
//String fix=filename.substring(filename.lastIndexOf("."),filename.length())
// String newfile = newfilename+fix;
String filePath = fileUploadPath+filename;//文件保存的地址及名称
File files = new File(filePath);
//检查文件夹是否存在
if(!files.getParentFile().exists()){
files.getParentFile().mkdirs();//新建文件夹
}
name.transferTo(files);//写入文件
}
}
return true;
}
}

二、文件下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class DownloadUtil {
public boolean download(String path, String name, HttpServletRequest request, HttpServletResponse response){

FileInputStream fileIn = null;
ServletOutputStream out = null;
try {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name+".PNG", "UTF-8"));
File file;
String filePathString = path + name+".PNG";
file = new File(filePathString);
fileIn = new FileInputStream(file);
out = response.getOutputStream();
byte[] outputByte = new byte[1024];
int readTmp = 0;
while ((readTmp = fileIn.read(outputByte)) != -1) {
out.write(outputByte, 0, readTmp); //并不是每次都能读到1024个字节,所有用readTmp作为每次读取数据的长度,否则会出现文件损坏的错误
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileIn.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
}