您的位置:首页 > 编程语言 > Java开发

spring MVC文件上传和下载

2016-02-20 16:36 471 查看
//上传

controller:

@RequestMapping(value = "uploads.do")

public ModelAndView upload(

@RequestParam(value = "add_attach_stcd",required = false) String add_attach_stcd,

@RequestParam(value = "add_attach_tm",required = false) Date add_attach_tm,

@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {

//图片路径

String path = request.getSession().getServletContext().getRealPath("upload");

//图片原始名称

String originalFilename = file.getOriginalFilename();

// String fileName = new Date().getTime()+".jpg";

//新的图片名称

String newFileName=UUID.randomUUID()+originalFilename.substring( originalFilename.lastIndexOf("."));

//常见文件类型

String pictureSuffix = ".jpg.jpeg.png.gif.psd.bmp";

String videoSuffix = ".mp4.avi.mpeg.3gp.mov.exe";

String documentSuffix=".word.zip.pdf.excel.ppt.rtf.xlsx.txt.doc.xls.wpd.html.htm";

//文件类型

int fileType = 0;

if (newFileName.lastIndexOf(".") != -1) {

String suffix = newFileName.substring(newFileName.lastIndexOf(".")).toLowerCase();

// 判断是图片还是视频类型

if (pictureSuffix.indexOf(suffix) != -1) {

fileType = 1;

} else if (videoSuffix.indexOf(suffix) != -1) {

fileType = 2;

}else if (documentSuffix.indexOf(suffix) != -1) {

fileType = 3;

}

}

System.out.println("附件类型:"+fileType);

System.out.println("附件路径:"+path);

File targetFile = new File(path, newFileName);

if(!targetFile.exists()){

targetFile.mkdirs();

}

Date now = new Date();

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式

String nowtime = dateFormat.format( now );

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

java.util.Date time=null;

try {

time= sdf.parse(sdf.format(new Date()));

} catch (ParseException e1) {

e1.printStackTrace();

}

System.out.println(nowtime);

//文件信息保存到数据库里

StationAttach attach=new StationAttach();

attach.setStcd(add_attach_stcd);

attach.setTm(time);

attach.setAttach_desc(newFileName);

attach.setAttach_url(path);

attach.setAttach_type(fileType);

attachservice.addStationAttach(attach);;

//保存

try {

file.transferTo(targetFile);

} catch (Exception e) {

e.printStackTrace();

}

model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+newFileName);

return new ModelAndView(new RedirectView("attach.do"),null);

}

jsp:

<form action="uploads.do" method="post" id="add_form" enctype="multipart/form-data">

<table style="border-spacing:15px" id="fileid">

<tr>

<td>测站编码</td>

<td>

<select id="add_attach_stcd" name="add_attach_stcd">

<option value=" " selected="selected">请选择</option>

<c:forEach items="${sessionScope.czbm}" var="item2">

<option value="${item2.stcd}"> ${item2.stcd}</option>

</c:forEach>

</tr>

<tr><td>

添加附件

</td>

<td><input type="file" name="file" ></td>

</tr>

<tr>

<td colspan="3" align="center" >

<div style="float:middle;'">

<div class="btn save_btn" onclick="submit_form('add_form')" style="float:right;'" ></div>

</div>

</td>

<td colspan="3" align="center" >

<div style="float:middle;'">

<div class="btn close_btn" model-close="add" style="float:left;" ></div>

</div>

</td>

</tr>

</table>

</form>

//下载

controller里:

@RequestMapping("download")

public String download( HttpServletRequest request,

HttpServletResponse response) {

String fileName=request.getParameter("fileName");

String path=uploadPath;

//获得第一个点的位置

int index=fileName.indexOf("/");

//根据第一个点的位置 获得第二个点的位置

index=fileName.indexOf("/", index+1);

//根据第二个点的位置,截取 字符串。得到结果 result

String result=fileName.substring(index);

//根据第二个点的位置 获得第三个点的位置

index=fileName.indexOf("/", index+2);

String result2=fileName.substring(index);

String result3=result2.replace("/", "");

response.setCharacterEncoding("utf-8");

response.setContentType("multipart/form-data");

response.setHeader("Content-Disposition", "attachment;fileName="

+ result3);

try {

InputStream inputStream = new FileInputStream(new File(path

+result));

OutputStream os = response.getOutputStream();

byte[] b = new byte[2048];

int length;

while ((length = inputStream.read(b)) > 0) {

os.write(b, 0, length);

}

os.close();

inputStream.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

jsp页面:

<td>${item.attach_url}<a href="download.do?method=download&fileName=${item.attach_url}">下载</a></td>



数据库:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: