java web picture upload and file upload example details

  • 2020-05-17 05:28:58
  • OfStack

java web picture upload and file upload

Picture upload and file upload are essentially the same, the image itself is a file. File upload is to upload pictures to the server, although there are many ways, but the underlying implementation is the file read and write operations.

Matters needing attention

1.form form 1 must have the property enctype="multipart/ form-data"

2. In order to ensure that the file can be uploaded successfully, the name property value of the file control should correspond to the control layer variable name 1 you submitted.

So, for example, the space name is file and you define it in the background

private File file; / / file control name

private String fileContentType; // picture type

private String fileFileName; / / file name

1. jsp page


<%@ page language="java" contentType="text/html; charset=UTF-8" 
  pageEncoding="UTF-8"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<meta http-equiv="pragma" content="no-cache" /> 
<base target="_self"> 
<title> File upload </title> 
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="file" value="file">
<input type="submit" value=" determine ">
</form>
</body>
</html>

1. Controller for page data to be submitted




package com.cpsec.tang.chemical.action;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.cpsec.tang.chemical.biz.LunboBiz;
import com.cpsec.tang.chemical.entity.Image;
import com.opensymphony.xwork2.ActionSupport;


@Controller("lunboAction")
public class LunboAction extends ActionSupport {
  /**
   * 
   */
  private static final long serialVersionUID = 1L;
  @Resource(name="lunboBiz")
  private LunboBiz lunboBiz;
  private Image image;
  private File file; //file The control of 
  private String fileContentType;// Image type 
  private String fileFileName; // The file name 
  private Integer number;
  
  public String findImage(){
    image=lunboBiz.findImage();
    return SUCCESS;
  }
  
  public String alterImage(){
    image=lunboBiz.findImage();
    return SUCCESS;
  }
  
  public String alterImage1(){
    HttpServletRequest request = ServletActionContext.getRequest();
    String root = request.getRealPath("/upload");// The server path to upload the image to 
    String names[]=fileFileName.split("\\.");
    String fileName="";
    if(names.length>=1){
      fileName=getRandomString(20)+"."+names[names.length-1];
    }
    String picPath="upload/"+fileName;// The path to save the image to the database 
    File file1=new File(root);
    try {
      FileUtils.copyFile(file, new File(file1,fileName));
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return SUCCESS;
  }
  
  /* To obtain 1 Random string */
  public String getRandomString(int length) { //length Represents the length of the generated string  
    String base = "abcdefghijklmnopqrstuvwxyz0123456789";   
    Random random = new Random();   
    StringBuffer sb = new StringBuffer();   
    for (int i = 0; i < length; i++) {   
      int number = random.nextInt(base.length());   
      sb.append(base.charAt(number));   
    }   
    return sb.toString();   
   }  

}

This is uploading files by copying and there are other ways

Method 2




@Controller("contractAction")
public class ContractAction extends ActionSupport {
  
  private final static String UPLOADDIR = "/files";// File upload path in webContent Set up under the 
  private File file; //input The control of 1 As the file 
  // Upload file name collection   
  private String fileFileName;  
  // Upload a collection of file content types   
  private String fileContentType; 
  
  private String filename;
 
  public String upload() throws FileNotFoundException, IOException{
    String path=uploadFile();// The file saves the path to the database 
  
    return SUCCESS;
  }
  
  // Perform upload function   
  @SuppressWarnings("deprecation")
  public String uploadFile() throws FileNotFoundException, IOException {  
    try {  
      InputStream in = new FileInputStream(file);  
      String dir = ServletActionContext.getRequest().getRealPath(UPLOADDIR); 
      File fileLocation = new File(dir); 
      // You can also manually create the target upload directory in the application root directory  
      if(!fileLocation.exists()){ 
        boolean isCreated = fileLocation.mkdir(); 
        if(!isCreated) { 
          // Target upload directory creation failed , Can do other processing , Such as throwing custom exceptions ,1 This should not be the case.  
          return null; 
        } 
      }
      // this.setFileFileName(getRandomString(20));
      String[] Name=this.getFileFileName().split("\\.");
      String fileName=getRandomString(20)+"."+Name[Name.length-1];
      this.setFileFileName(fileName);
      System.out.println(fileName);
      File uploadFile = new File(dir, fileName);
      OutputStream out = new FileOutputStream(uploadFile);  
      byte[] buffer = new byte[1024 * 1024];  
      int length;  
      while ((length = in.read(buffer)) > 0) {  
        out.write(buffer, 0, length);  
      }
      in.close();  
      out.close();  
      return UPLOADDIR.substring(1)+"\\"+fileFileName;
      } catch (FileNotFoundException ex) {
        return null;  
      } catch (IOException ex) {
        return null;  
    }  
  }
  
  
  public static String getRandomString(int length){
    String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    Random random=new Random();
    StringBuffer sb=new StringBuffer();
    for(int i=0;i<length;i++){
     int number=random.nextInt(62);
     sb.append(str.charAt(number));
    }
    return sb.toString();
  }  

}


In addition to single picture upload and multiple picture upload, the principle is a kind of


package com.cpsec.tang.chemical.action;

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;


/**
 *  Multiple file upload 
 */
public class FilesUploadAction extends ActionSupport {
     // Upload file storage path   
     private final static String UPLOADDIR = "/upload";  
     // Upload file collection   
     private List<File> file;  
     // Upload file name collection   
     private List<String> fileFileName;  
     // Upload a collection of file content types   
     private List<String> fileContentType;  
     
     public List<File> getFile() {  
       return file;  
     }  
 
     public void setFile(List<File> file) {  
       this.file = file;  
     }  
 
    public List<String> getFileFileName() {  
      return fileFileName;  
    }  
 
     public void setFileFileName(List<String> fileFileName) {  
       this.fileFileName = fileFileName;  
     }  
 
     public List<String> getFileContentType() {  
       return fileContentType;  
     }  
 
     public void setFileContentType(List<String> fileContentType) {  
       this.fileContentType = fileContentType;  
     }  
 
     
     public String uploadform() throws Exception {
       HttpServletRequest request = ServletActionContext.getRequest();
       String webpath=null;// Upload path 
       for (int i = 0; i < file.size(); i++) {  
         // Upload each file in a loop   
         uploadFile(i); 
         webpath="upload/"+this.getFileFileName().get(i);
       }
       return "SUCCESS";
     } 
   
 
    
    // Perform upload function   
     private String uploadFile(int i) throws FileNotFoundException, IOException {  
       try {  
         
         InputStream in = new FileInputStream(file.get(i));  
         String dir = ServletActionContext.getRequest().getRealPath(UPLOADDIR); 
         File fileLocation = new File(dir); 
         // You can also manually create the target upload directory in the application root directory  
         if(!fileLocation.exists()){ 
           boolean isCreated = fileLocation.mkdir(); 
           if(!isCreated) { 
             // Target upload directory creation failed , Can do other processing , Such as throwing custom exceptions ,1 This should not be the case.  
             return null; 
           } 
         } 
         String fileName=this.getFileFileName().get(i); 
         File uploadFile = new File(dir, fileName);
         OutputStream out = new FileOutputStream(uploadFile);  
         byte[] buffer = new byte[1024 * 1024];  
         int length;  
         while ((length = in.read(buffer)) > 0) {  
           out.write(buffer, 0, length);  
         }
         in.close();  
         out.close();  
         return uploadFile.toString();
       } catch (FileNotFoundException ex) {
         return null;  
       } catch (IOException ex) {
         return null;  
       }  
     }
   }

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: