File upload and download under SPRINGMVC and servlet (two ways to save file directory and save database BLOB)

Source: Internet
Author: User
Tags save file

Project involved in the upload and download of files, previously done under the STRUTS2, and today with Springmvc do again, found that the SPRINGMVC package is particularly good, basic without a few lines of code to complete, the following code to paste out:


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 directory try {String path = request.getsession (). Getservletcontext (). Getrealpath ("/");//File save directory, 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 the Springmvc upload file demo, one of the key step is that the spring configuration file to add File upload support:

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

File saving is done in two ways, one is the file directory of the direct storage server, the other is to put the file stream into the Database BLOB field (the project's special 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 is very simple and clear, right? It doesn't have to be as much code as the servlet.












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.