文件上传
jsp:
<form id="update_form" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="validate_body col-xs-9">
<input type="file" id="fileUpload" name="fileUpload"/>
</div>
</div>
</form>
java:
@RequestMapping(value = "/save")
public String save(ModelMap model, HttpServletRequest request)
{//TODO 保存
String dirPath = "/pdffiles/"; //文件夹名
dirPath = request.getRealPath(dirPath)+"/";
String fileName;
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> fileList = multipartRequest.getFiles("fileUpload");
for (MultipartFile mf : fileList) {
if(!mf.isEmpty()){
if (mf.getContentType().equals("application/pdf")){
fileName = UUID.randomUUID() + "." + FilenameUtils.getExtension(mf.getOriginalFilename());
String savePath = dirPath + fileName;
File file =new File(savePath);
if (!file.getParentFile().exists())
{
file.getParentFile().mkdirs();
}
InputStream in=mf.getInputStream();
FileOutputStream fos=new FileOutputStream(savePath);
byte[] buffer=new byte[1024];
while(in.read(buffer)>0){
fos.write(buffer);
fos.flush();
}
in.close();
fos.close();
getParames().put("instructionBookDirectory", savePath);
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
service.update(getParames());
return "redirect:list.jhtml";
}
文件下载
jsp:
<div>
<a href="downloadfile.jhtml?dir=${row.instructionBookDirectory}">下载</a>
</div>
java:
// 下载文件
@RequestMapping(value = "/downloadfile")
public void downloadfile(ModelMap model, HttpServletResponse response)
{
response.setContentType("charset=UTF-8");
Object dir = getParames().get("dir");
if(dir!=null){
File file = new File(dir.toString());
response.setHeader("Content-Disposition", "attachment; filename=a");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
try {
fis = new FileInputStream(file.getAbsolutePath());
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
int bytesRead = 0;
byte[] buffer = new byte[5 * 1024];
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
}catch(Exception e){
e.printStackTrace();
}finally {
try {
bis.close();
bos.close();
fos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}