SpringMvc3+extjs4 realize upload and download function

  • 2020-08-22 21:58:38
  • OfStack

The example of this paper shares the specific code of SpringMvc3+extjs4 to upload and download for your reference, the specific content is as follows

Recently life has been very full, people 1 has been busy learning new things. This is a problem I met recently, I searched for Baidu n for a long time, and finally found a solution!

Foreground code:


<script> 
 Ext.onReady(function() {

  Ext.create('Ext.form.Panel', {
   title : ' File upload ',
   width : 400,
   bodyPadding : 10,
   frame : true,
   renderTo : document.body,
   items : [ {
    xtype : 'filefield',
    name : ' file ',
    fieldLabel : 'File',
    labelWidth : 50,
    msgTarget : 'side',
    allowBlank : false,
    anchor : '100%',
    buttonText : ' Please select file ...'
   } ],

   buttons : [ {
    text : ' upload ',
    handler : function() {
     var form = this.up('form').getForm();
     if (form.isValid()) {
      form.submit({
       url : ' Root path /fileUploadDown/fileUpload',
       waitMsg : ' Uploading file in progress ...',
       success : function(fp, o) {
        Ext.Msg.alert(' Upload file successfully !');
       }
      });
     }
    }
   } ]
  });

 });
</script>

Background code:


/**
* Record return result */
 class ExtJSFormResult {

 private boolean success;

 public boolean isSuccess() {
  return success;
 }

 public void setSuccess(boolean success) {

 }

 public String toString() {
  return "{success:" + this.success + "}";
 }
}
 

class FileUploadBean {

  private CommonsMultipartFile file;

  public CommonsMultipartFile getFile() {
   return file;
  }

  public void setFile(CommonsMultipartFile file) {
   this.file = file;
  }
}

/**
 *  Upload and download files 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/fileUploadDown")
public class FileUploadAndDownController {
 
 private static int countter=1; // define 1 A counter , Rename for uploading files 
 
 @Autowired
 private ProAnnexDao<ProAnnex> proAnnextDao;
 
 

 public void setProAnnextDao(ProAnnexDao<ProAnnex> proAnnextDao) {
  this.proAnnextDao = proAnnextDao;
 }

 @RequestMapping(value="fileUpload",method = RequestMethod.POST)
 public @ResponseBody String create(RedirectAttributes redirectAttributes,FileUploadBean uploadItem, 
   BindingResult result,HttpSession session){
  // Get the root path 
  String uploadFolderPath = session.getServletContext().getRealPath("/"); 
  ExtJSFormResult extjsFormResult = new ExtJSFormResult();
  try {
   
   if (result.hasErrors()) {
    for (ObjectError error : result.getAllErrors()) {
     System.err.println("Error: " + error.getCode() + " - "
       + error.getDefaultMessage());
    }

    //  Set up the ExtJS return  - error
    extjsFormResult.setSuccess(false);

    return extjsFormResult.toString();
   }

   MultipartFile file = uploadItem.getFile();
   String fileName = null;
   InputStream inputStream = null;
   OutputStream outputStream = null;
   if(file.getSize()>0){
     System.out.println("File Size:::" + file.getSize());
    if(file.getSize()>5242880){
      System.out.println("File Size:::" + file.getSize());
      extjsFormResult.setSuccess(false);
     return "error";
    }
    
    inputStream = file.getInputStream();
  
    File newFile = new File(uploadFolderPath + "fileUpload/");
    // If the file path does not exist, create it 1 a 
    if(!newFile.exists()){
     newFile.mkdirs();
    }
    // Get file name 
    String name=file.getOriginalFilename();
    // Query the database for the existence of such a file name 
    Long count=proAnnextDao.isRepeatName(name);
    // If there is 1 Sample file name , Just carry on from the naming 
    if (count>0) {
     name=name.substring(0, name.lastIndexOf("."))+"("+(countter++)+")"+name.substring(name.lastIndexOf("."));
    }
    
    fileName = uploadFolderPath + "fileUpload/" + name;
    outputStream = new FileOutputStream(fileName); 
    int readBytes = 0;
    byte[] buffer = new byte[10000];
    while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
      outputStream.write(buffer, 0, readBytes);
    }
    
    outputStream.close();
    inputStream.close();
    
    
   }

   //  Set up the ExtJS return  - sucsess
   extjsFormResult.setSuccess(true);
  } catch (Exception e) {
   
   e.printStackTrace();
   //  Set up the ExtJS return  - error
  
   extjsFormResult.setSuccess(false);
  }
  

  return extjsFormResult.toString();
 }
 

}

springMvc. xml (this filename may differ from the actual project) configuration:


<!--  Upload a file , Limit size configuration  -->
  <bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!--resolveLazily Property is enabled to defer file parsing in order to be in the Upload Catches a file size exception -->
  <property name="resolveLazily" value="true"/>
  <property name="maxUploadSize" value="5242880" />
 </bean>
 
 
 <!--  Will not be able to mapping to Controller the path to default servlet handler To deal with   --> 
 <mvc:default-servlet-handler/><!--  Use the default servlet To respond to static files  -->
 <!--  Upload and download files  -->
 <mvc:view-controller path="/" view-name="redirect:/fileUploadDown"/>

So that's uploading the file.

What about downloads?

The download is easy, the code is as follows:


@RequestMapping("/downloadFile") 
 public void download(@Valid @ModelAttribute("downLoadName") String downLoadName,
   HttpServletResponse response,HttpSession session,BindingResult result,HttpServletRequest request) throws IOException { 
  
  response.setCharacterEncoding("UTF-8");
  request.setCharacterEncoding("UTF-8");
  // Gets the path to the file 
  String url=session.getServletContext().getRealPath("/")+"/fileUpload/"+downLoadName;
  System.out.println(url);
  File file=new File(url);
  
  InputStream input = FileUtils.openInputStream(file); 
  byte[] data = IOUtils.toByteArray(input); 
 
  //System.out.println(" The file name :"+downLoadName);
  response.reset(); 
  // Sets the header information for the response ( The solution to the Chinese problem )
  response.setHeader("content-disposition","attachment;fileName="+URLEncoder.encode(downLoadName, "UTF-8"));
  response.addHeader("Content-Length", "" + data.length); 
  response.setContentType("application/octet-stream; charset=UTF-8"); 
  
  IOUtils.write(data, response.getOutputStream()); 
  IOUtils.closeQuietly(input); 
  
 }

As long as there is 1 connection address on the interface: window. location. href=" root path /fileUploadDown/downfile/downLoadName="+name; So you can download it... Hyperlink is written in the basic 1, here is not to say more.


Related articles: