上传代码
@ResponseBody
@RequestMapping(value = "upload", method = { RequestMethod.POST })
public String upload(HttpServletRequest request, HttpServletResponse response) {
long startTime = System.currentTimeMillis();
DiskFileItemFactory factory = new DiskFileItemFactory(); // 基于磁盘文件项目创建一个工厂对象
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> itr = items.iterator();// 枚举方法
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next(); // 获取FileItem对象
if (!item.isFormField()) {// 判断是否为文件域
if (item.getName() != null && !item.getName().equals("")) {// 判断是否选择了文件
long upFileSize = item.getSize(); // 上传文件的大小
String fileName = item.getName(); // 获取文件名
String key = aliyunOssService.uploadFile(item.getInputStream(), fileName);
System.out.println("times:" + (System.currentTimeMillis() - startTime));
System.out.println("fileName:" + fileName + ",size:" + upFileSize + ",key:" + key);
return key;
}
}
}
} catch (FileUploadException | IOException e) {
e.printStackTrace();
}
return "";
}
下载代码
@ResponseBody
@RequestMapping(value = "/apk/download/{path}", method = { RequestMethod.GET })
public String download(HttpServletRequest request, HttpServletResponse response, @PathVariable String path) {
InputStream is = null;
OutputStream os = null;
try {
is = aliyunOssService.getZipFile(path);
response.reset();
response.addHeader("Content-Disposition", aliyunOssService.getFileName(path));
os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}