springmvc之文件上传、下载
1、接收到的是图片的流时
//上传头像 @RequestMapping(value = "/uploadHeadSculpture", method = RequestMethod.POST) @ResponseBody public String uploadHeadSculpture(@RequestParam("photo") String file) { User user = (User) SecurityUtils.getSubject().getSession().getAttribute("curr_user"); //获取文件格式 String postfix = file.split("/")[1].split(";")[0]; //获取图片的Base64码 String str = file.split(",")[1]; String url = ""; BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解码 byte[] bytes = decoder.decodeBuffer(str); for (int i = 0; i < bytes.length; ++i) { // 调整异常数据 if (bytes[i] < 0) { bytes[i] += 256; } } long title = Calendar.getInstance().getTimeInMillis(); //获取系统路径并设定文件保存的目录 String dir = ServiceConfigUtil.getValue("imgpath");//图片的上传路径,我这里是从工程的配置文件获取的 String fileName = title + "." + postfix; // 生成jpeg图片 FileUtils.writeByteArrayToFile(new File(dir, fileName), bytes); String lookUserPhoto = ServiceConfigUtil.getValue("lookUserPhoto");//图片的访问路径,我这里是从工程配置文件获取的,可以自己定义。如果你的图片保存在工程目录下,可以直接用dir+fileName url = lookUserPhoto + fileName;//保存到数据库的图片访问路径 /××
×保存url到数据库
××/
} catch (Exception e) {return "no"; }return "yes"; }
注:接收参数file值的一个基本格式
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAdiUlEQVR........."
2、接收到的是file文件直接上传
@RequestMapping(value={"/saveOrUpdate"},method=RequestMethod.POST) public String saveOrUpdate(Person p, @RequestParam("photo") MultipartFile file, HttpServletRequest request) throws IOException{ if(!file.isEmpty()){ ServletContext sc = request.getSession().getServletContext(); String dir = sc.getRealPath(“/upload”); //设定文件保存的目录 String filename = file.getOriginalFilename(); //得到上传时的文件名 FileUtils.writeByteArrayToFile(new File(dir,filename), file.getBytes()); p.setPhotoPath(“/upload/”+filename); //设置图片所在路径 System.out.println("upload over. "+ filename); } ps.saveOrUpdate(p); return "redirect:/person/list.action"; //重定向 }
2.1、页面
<form action="/saveOrUpdate" enctype="multipart/form-data" method="post"> <input type="file" name="photo"> <input type="submit" value="commit"> </form>
2.2、需要在springmvc配置文件中添加
<!--上传文件-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000000000"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
3、文件下载
private void downFile(String filename, String realPath, HttpServletResponse response) throws IOException { try { filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { log.warn("文件转码出现异常异常信息为:" + ExceptionUtil.print(e)); } log.debug("下载的文件名:" + filename); log.debug("下载的文件路径:" + realPath); OutputStream os = null; InputStream inputStream = null; try { response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;fileName=" + filename); inputStream = new FileInputStream(realPath); os = response.getOutputStream(); byte[] b = new byte[1024]; int length; while ((length = inputStream.read(b)) != -1) { os.write(b, 0, length); } os.flush(); } catch (IOException e) { log.warn("下载文件出现异常,异常信息为:" + ExceptionUtil.print(e)); } finally { inputStream.close(); os.close(); } }