直接上代碼
該配置的還需要spring容器配置好.例如上傳的組件..
下載
public void downLoadFile(HttpServletResponse response, File file) {
if (file == null || !file.exists()) {
return;
}
OutputStream out = null;
try {
response.reset();
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
out = response.getOutputStream();
out.write(FileUtils.readFileToByteArray(file));
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
下載的另一種方法
@RequestMapping("/download")
public ResponseEntity<byte[]> download(Integer bid, HttpServletRequest httpServletRequest,
HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");
if(bid==null){
response.getWriter().print("下載的文件不存在..");
}
Download download= downloadService.selectByBid(bid);
if(download==null){
response.getWriter().print("下載的文件不存在..");
return null;
}
File file=new File(httpServletRequest.getRealPath("/")+download.getFileurl());
if(file.exists()==false){
response.getWriter().print("下載的文件不存在..");
}
HttpHeaders headers = new HttpHeaders();
String fileName=new String((download.getDownbook()+".pdf").getBytes("UTF-8"),"iso-8859-1");//爲了解決中文名稱亂碼問題
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
// headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
上傳(多文件)
@RequestMapping("/upload.do")
public String upload(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 這裏我用到了jar包
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile((String) iter.next());
if (file != null) {
String fileName = file.getOriginalFilename();
String path1 = Thread.currentThread()
.getContextClassLoader().getResource("").getPath()
+ "download" + File.separator;
// 下面的加的日期是爲了防止上傳的名字一樣
String path = path1
+ new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date()) + fileName;
File localFile = new File(path);
file.transferTo(localFile);
}
}
}
return "uploadSuccess";
}