springmvc Upload files 、 download 、 preview . Stored in a database in binary form .
In the database about the field of the incoming attachment, I wrote 2 individual : A store of content accessory, A suffix for storing files filetype

Upload : The first thing you need to 2 It's a must jar:

XXX-servlet.xml Write upload interception in :
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolve">  
      <property name="maxUploadSize" value="100000" />  

jsp page :
<form method="POST" action=" Submit the address " name="frm" enctype="multipart/form-data">   
       <input type="file" name="accessory"/><br>  
        <input type="submit" onclick="return checkacc();"/><br>  
<!-- If you need to verify the type of the incoming file , Can pass js verification , I verified this when I submitted it -->
function checkacc(){
    var postfix = frm.accessory.value.substring(frm.accessory.value.lastIndexOf(".")+1); // Get the regular expression of the suffix of the selected upload file   
          if(!(postfix == "jpg"||postfix == "pdf"))   
      alert(' Incorrect file type , Please select .jpg perhaps .pdf file !');   
      return false;   

notes : I used to use servlet Write the file upload , Join in enctype="multipart/form-data" This field , It will result in no access to form The values of other fields in , But in springmvc There will be no such problem .

java Controller class :
public ModelAndView addSaleStock(HttpServletRequest request,HttpServletResponse response) throws Exception {
       MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
       MultipartFile file = multipartRequest.getFile("accessory");
       byte[] inputData = null;
       String fileType="";
             inputData = inputStream2Byte(file.getInputStream());
             String s=file.getOriginalFilename();
                 // The object class of the table in the database (model), Generally speaking, it means hibernate Medium po
                 ValidRegstock validRegstock = new ValidRegstock();
                      try {
                             // Go and see service class
           msg = " Add success !";
             } catch (Exception e) {
            msg = " Add failure !";
                  return new ModelAndView( The return address );

java service class :
public void addSendRegStock(ValidRegstock validRegstock)
throws Exception {
   // Go and see dao class

java  dao class :
public void add(ValidRegstock validRegstock) {
       String sql="insert into Z_ValidRegstock(accessory,filetype) values(?,?)";
       // Here we use the form of data connection to store in the database
       Connection conn=null;
       try {
conn = getJdbcTemplate().getDataSource().getConnection();
PreparedStatement ps=conn.prepareStatement(sql);
          // Be careful : Large object type What we put in is bytes[], Here set object
ps.setObject(1, validRegstock.getInputData());
ps.setString(2, validRegstock.getFiletype());
       } catch (SQLException e) {

So you can upload . It should be noted that :

Some friends can use :
Object[] params={validRegstock.getInputData()};
int[] dataTypes={Types.XXX};
getJdbcTemplate().update( sql, params, dataTypes);
It's a way of saving , Here I use Types.XXX Because I tried Types.blob,Types.other It's not easy to wait . And I put bytes[] use hibernate To java.sql.blob If you don't deposit it It's not easy to use . There will be a type mismatch java.oracle.blob. So if you are successful in this way, please tell me . thank you

Preview is similar to download . The same service, The same dao, Let me start with dao and service:
java dao class :
public List accessorySel(String id){
StringBuffer sql=new StringBuffer("");
sql.append("select accessory,filetype from Z_ValidRegstock where regstockId='");
Connection conn=null;
statement state=null;
ResultSet rs = null;
List list=new ArrayList();
try {
    if (rs.next()) {
                   // This blob yes java.sql.Blob Type of
Blob blob = rs.getBlob("accessory");
String filetype=rs.getString("filetype");
list.add(0, blob);
} catch (SQLException e) {
return list;

java service class :
public List accessorySel(String id){
return regStockDao.accessorySel(id);

java Controller class :
preview :
public ModelAndView getAccessoryView(HttpServletRequest request,HttpServletResponse response) throws Exception {
String id=request.getParameter("id");
List list=this.getBeanOfValidRegstockService().accessorySel(id);
Blob blob=(Blob) list.get(0);
String filetype=(String) list.get(1);
int length = (int) blob.length();
byte[] bImage = new byte[length];
InputStream is = new BufferedInputStream(blob.getBinaryStream());
is.read(bImage, 0, length);
OutputStream out = response.getOutputStream(); 
return null;

download :
public ModelAndView getAccessoryDownload(HttpServletRequest request,HttpServletResponse response) throws Exception {
         //jsp From here To download the data corresponding to the attachment id
String id=request.getParameter("id");
List list=this.getBeanOfValidRegstockService().accessorySel(id);
Blob blob=(Blob) list.get(0);
String filetype=(String) list.get(1);
OutputStream fos = response.getOutputStream();
InputStream is = new BufferedInputStream(blob.getBinaryStream());
          // If the download is in tabular form , There may be confusion . Add the following sentence :( Other cases of garbled code under their own Baidu .)
// Pop up the save box statement , You can fill in the default name and type
byte[] buffer = new byte[1024];
int size = 0;
while ((size = is.read(buffer)) != -1) {
      fos.write(buffer, 0, size);
      return null;

springmvc File down 、 upload 、 preview . Stored in a database in binary form ( Reprint ) More articles about

  1. JavaScrip Native multi file upload and preview Multi-browser compatibility

    JavaScrip Native multi file upload and preview Multi-browser compatibility html Code block <div class="container"> <label> Please select an image file :& ...

  2. form File upload and preview in form series

    File upload and preview Form Submit Ajax Upload files opportunity : If sent [ file ]:->iframe, jQurey(), false Ajax preview import os img_path = os.path.j ...

  3. combination bootstrap fileinput Plug ins and Bootstrap-table Form plug-in , File upload 、 preview 、 Submitted imports Excel Data operation flow

    1.bootstrap-fileinpu A brief introduction In front of the essay , I introduced Bootstrap-table The specific project application process of the form plug-in , This essay introduces another Bootstrap FieInput Use of plug-ins , ...

  4. servlet File upload , preview , Download and delete

      One . preparation 1.1 File upload plugin :uploadify: 1.2 File upload required jar package :commons-fileupload-1.3.1.jar and commons-io-2.2.jar 1.3 Number of generals ...

  5. form Inside the file upload and preview

    Actually form It can't be nested inside form Of , If form There are picture uploads and other things input box , We want to upload images and preview images , And then put the other input Box completed , And then submit the whole form , There are two ways ! Mode one : Click the upload button ...

  6. JQ Preview function before uploading image file

    1. Prepare one first div onchange Triggering event <input  type="file" onchange="preview(this)" >< ...

  7. Django File upload and preview 、 Storage

    Ideas : The files are uploaded through the front end input label ,input Set up display:none attribute . Content display needs to let the front end go through <img> Tag reads the content of the picture , Can pass <label> Tag connection < ...

  8. Support multi file upload , preview , Drag and drop , be based on bootstra Upload plug-in for fileinput Of ajax Asynchronous upload

    First you need to import some js and css file <link href="__PUBLIC__/CSS/bootstrap.css" rel="stylesheet"&g ...

  9. Support multi file upload , preview , Drag and drop , be based on bootstrap Upload plug-in for fileinput Of ajax Asynchronous upload ( Reprint )

    First you need to import some js and css file <link href="__PUBLIC__/CSS/bootstrap.css" rel="stylesheet"&g ...

Random recommendation

  1. Reprint :TypeScript Introduction and 《TypeScript Introduction to Chinese 》

    brief introduction TypeScript Is a free and open source programming language developed by Microsoft . It is JavaScript A superset of , And it essentially adds optional static typing and class-based object-oriented programming to the language . Anders · hejlsberg ,C# The chief architecture of ...

  2. modern DOJO( translate )

    http://dojotoolkit.org/documentation/tutorials/1.10/modern_dojo/index.html You may not have doio It's been a while , Or you've always wanted to keep ...

  3. MYSQL introduction ( 3、 ... and )

    Index introduction An index is an index of one or more columns in a database table ( for example ,employee The name of the table (name) Column ) The structure of sorting the values of . If you want to find a particular employee by his or her last name , Compared to searching all the rows in the table , Indexing helps to get information faster ...

  4. view The principle of drawing

    turn :http://blog.csdn.net/berber78/article/details/42069301 Customize UI Control , Need to inherit View Class or View Subclasses of , And overloading View Some methods in class , No need ...

  5. LED Calculation of current limiting resistance

    Most of the time, it's used in the circuit LED Give instructions , This involves the current limiting resistor , How to choose this ? For example , Patch blue LED datasheet The above parameters are as follows Pay attention to understanding LED Datasheet Parameters on . The three most important parameters are as follows : ...

  6. im Edit command summary

    One . VIM The highlighted Get into vim after , Enter the following command in normal mode , Turn on php Code highlight   :syntax enable   :source $VIMRUNTIME/syntax/php.vim   Two . ...

  7. PHP 5 data type

    This page is from http://www.runoob.com/php/php-datatypes.html String( character string ), Integer( integer ), Float( floating-point ), Boolean( Boolean type ...

  8. Mac build Hadoop Source reading environment

    1. This time Hadoop The reading tools used in the source code reading environment are idea,Hadoop The version is 2.7.3. The tools that need to be installed include idea.jdk.maven.protobuf etc. 2.jdk, The version used is 1.8 edition , stay jdk Officer, ...

  9. Java web In the common coding garbled problem ( One )

    Recently in to see Java web Chinese coding problem in Chinese , It is hereby recorded that . This article will introduce common coding methods and Java web Common solutions to the problem of Chinese garbled code in English : One . Common coding methods : 1.ASCII code as everyone knows , This is the simplest code . ...

  10. Vuejs example -00Vuejs2.0 The whole family is united ELementUI Making background management system

    Vuejs2.0 The whole family is united ELementUI Making background management system 0: Introduction of system environment 1: Vuejs example -01 Use vue-cli Scaffolding Vue.js project 2: Vuejs example -02Vue.js Project set ...