Java文件上传下载
/**
* 上传文件
*/
public String uploadFile() throws IOException, Exception {
if (getRequestContext().haveUploadFile()) {
String channelId = getRequest().getParameter("channelId");
JfileItem fileItem = getRequestContext().getUploadFiles().get(0);
// 文件名
String fileName = fileItem.getName();
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String uploadFileName = df.format(new Date()) + fileName;
// 文件类型
int n = fileName.lastIndexOf(".");
String type = fileName.substring(n + 1);
// 上传路径
String path = getRequest().getServletContext().getRealPath("") + "\\uploadfiles\\";
//获取输出流
OutputStream os = new FileOutputStream(path + uploadFileName);
// 获得输入流
InputStream is = fileItem.getInputStream();
// 写入
byte[] buffer = new byte[512];
int temp;
while ((temp = is.read(buffer)) != (-1)) {
os.write(buffer, 0, temp);
}
os.flush();
os.close();
is.close();
// 将文件信息写入数据库
FileUpload fileUpload = new FileUpload();
fileUpload.setFileName(fileName);
fileUpload.setFileLocation(uploadFileName);
fileUpload.setFileChannelId(channelId);
fileUploadService.save(fileUpload);
}
return getOutJson().toString();
}
/**
* 下载文件
*/
public String downloadFile() throws Exception {
String id = getRequest().getParameter("id");
FileUpload fileUpload = fileUploadService.getById(id);
// 根路径
String path = getRequest().getServletContext().getRealPath("") + "\\uploadfiles\\";
// 下载文件的路径
String filePath = path + fileUpload.getFileLocation();
// 文件名
String fileName = fileUpload.getFileName();
fileName = URLEncoder.encode(fileName, "UTF-8");
HttpServletResponse response = getResponse();
// 设置文件ContentType类型,自动判断下载文件类型
response.setContentType("multipart/form-data");
// 设置编码
response.setCharacterEncoding("utf-8");
// 设置文件头,最后一个参数是设置下载文件名
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
// 通过文件路径获得File对象
File file = new File(filePath);
FileInputStream is = new FileInputStream(file);
// 通过response获取OutputStream对象
OutputStream os = response.getOutputStream();
// 写入
byte[] buffer = new byte[512];
int i;
while ((i = is.read(buffer)) != -1) {
os.write(buffer, 0, i);
}
os.flush();
os.close();
is.close();
return getOutJson().toString();
}
原文:https://www.cnblogs.com/creaky/p/10801289.html