Springmvc and servlets upload and download files (two ways to keep folders and store database blobs)

Source: Internet
Author: User
Tags save file

Participate in the project file upload and download. Once the struts2 is finished, SPRINGMVC it again today. Find SPRINGMVC Special Good package, basically do not have a few lines of code can be completed, the following code paste:


fileupanddown.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "%>
Fileupanddowncontroller.java

@RequestMapping (value = "/fileupload") public String Upload (@RequestParam (value = "File", Required = False) Multipartfile File,httpservletrequest request, Modelmap model) throws IOException {/*//Way one: Save file Folder try {String path = Request.getsessio N (). Getservletcontext (). Getrealpath ("/");//File Save folder, also customizable as absolute path string fileName = File.getoriginalfilename ();// Getoriginalfilename and GetName are not the same Oh System.out.println (path); File TargetFile = new file (path, fileName), if (!targetfile.exists ()) {targetfile.mkdirs ();} File.transferto (targetfile); Model.addattribute ("Upload.message", Request.getcontextpath () + "/upload/" + FileName);} catch (Exception e) {e.printstacktrace ();} *///mode two: Save inbound map<string, object> insertmap = new hashmap<string, Obje Ct> (); Insertmap.put ("Byt", File.getbytes ()); Insertmap.put ("FileName", File.getoriginalfilename ()); int flag = Fileupanddownmapper.savefileinfo (Insertmap), if (Flag > 0) model.addattribute ("Upload.message", "success"); Elsemodel.addattribute ("Upload.message", "FAilure "); return"/core/param/businessparam/uploadresult ";} 

Fileupanddownmapper.xml (the corresponding database is DB2, save blob type)

<?xml version= "1.0" encoding= "UTF-8"?

><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mappernamespace= "Com.xx.persistence.FileUpAndDownMapper" ><resultmap id= "Filebean" type= " Com.xx.web.FileUpAndDown "><id column=" id "property=" id "jdbctype=" INTEGER "/><result column=" FILENAME " Property= "FileName" jdbctype= "VARCHAR"/> <result column= "TESTA" property= "TESTA" javatype= "byte[" "jdbctype=" BLOB "typehandler=" Org.apache.ibatis.type.BlobTypeHandler "/> <result column=" FILESTREAM "property=" FileStream "javatype=" byte[] "jdbctype=" BLOB "typehandler=" Org.apache.ibatis.type.BlobTypeHandler "/></ resultmap> <insert id= "Savefileinfo" parametertype= "Java.util.HashMap" >insert into BLOBTest (FILENAME, FILESTREAM) VALUES (#{filename}, #{byt, javatype=byte[], Jdbctype=blob, typehandler= Org.apache.ibatis.type.BlobTypeHandler}) </insert> <select id= "GETFILEBYPK" resultmap= "Filebean" parametertype= "int" > SELect * from BLOBTest WHERE Id=${value} </select></mapper>


uploadresult.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

The above is a key step in the demo of uploading files under SPRINGMVC. Add support for file uploads in the spring configuration file:

<!--support uploading files--><bean id= "Multipartresolver" class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver "/>

File saving is done in two ways, one is the file folder of the direct storage server, and the other is to put the file stream into the Database BLOB field (Project requirements)

Here is the code for the file download:

@ResponseBody @requestmapping (value = "/filedownload") public void FileDownload (HttpServletRequest request, HttpServletResponse response) throws IOException {String fileId = Request.getparameter ("FileId"); Fileupanddown file = FILEUPANDDOWNMAPPER.GETFILEBYPK (Integer.parseint (fileId)); byte[] FileStream = File.getfilestream (); String fileName = File.getfilename ();//Download the file Response.setcontenttype ("Application/octet-stream") in the form of a stream; Response.setheader ("Content-disposition", "attachment; Filename=\ "" + New String (Filename.getbytes ("gb2312"), "iso8859-1") + "\" "); OutputStream toclient = new BUFFEREDOUTPUTST Ream (Response.getoutputstream ()); Toclient.write (FileStream); Toclient.flush (); Toclient.close ();}

Springmvc File upload download very easy right? Don't like servlets in so much code.












Springmvc and servlets upload and download files (two ways to keep folders and store database blobs)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.