欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java web圖片上傳和文件上傳實(shí)例詳解

 更新時(shí)間:2016年11月21日 10:02:36   投稿:lqh  
這篇文章主要介紹了java web圖片上傳和文件上傳實(shí)例詳解的相關(guān)資料,這里提供了兩種方法及示例代碼,需要的朋友可以參考下

java web圖片上傳和文件上傳

圖片上傳和文件上傳本質(zhì)上是一樣的,圖片本身也是文件。文件上傳就是將圖片上傳到服務(wù)器,方式雖然有很多,但底層的實(shí)現(xiàn)都是文件的讀寫操作。

注意事項(xiàng)

1.form表單一定要寫屬性enctype="multipart/form-data"

2.為了能保證文件能上傳成功file控件的name屬性值要和你提交的控制層變量名一致,

例如空間名是file那么你要在后臺(tái)這樣定義

private File file; //file控件名

private String fileContentType;//圖片類型

private String fileFileName; //文件名

1.jsp頁(yè)面

<%@ 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>文件上傳</title> 
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="file" value="file">
<input type="submit" value="確定">
</form>
</body>
</html>

1.頁(yè)面數(shù)據(jù)需要提交的Controller



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控件名
  private String fileContentType;//圖片類型
  private String fileFileName; //文件名
  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");//圖片要上傳到的服務(wù)器路徑
    String names[]=fileFileName.split("\\.");
    String fileName="";
    if(names.length>=1){
      fileName=getRandomString(20)+"."+names[names.length-1];
    }
    String picPath="upload/"+fileName;//圖片保存到數(shù)據(jù)庫(kù)的路徑
    File file1=new File(root);
    try {
      FileUtils.copyFile(file, new File(file1,fileName));
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return SUCCESS;
  }
  
  /*獲取一條隨機(jī)字符串*/
  public String getRandomString(int length) { //length表示生成字符串的長(zhǎng)度 
    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();   
   }  

}

這是通過(guò)復(fù)制的方式上傳文件,還有其他方式

方法二



@Controller("contractAction")
public class ContractAction extends ActionSupport {
  
  private final static String UPLOADDIR = "/files";//文件上傳的路徑,在webContent下建立
  private File file; //input控件名一定為file 
  //上傳文件名集合  
  private String fileFileName;  
  //上傳文件內(nèi)容類型集合  
  private String fileContentType; 
  
  private String filename;
 
  public String upload() throws FileNotFoundException, IOException{
    String path=uploadFile();//文件保存數(shù)據(jù)庫(kù)的路徑
  
    return SUCCESS;
  }
  
  //執(zhí)行上傳功能  
  @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); 
      //此處也可以在應(yīng)用根目錄手動(dòng)建立目標(biāo)上傳目錄 
      if(!fileLocation.exists()){ 
        boolean isCreated = fileLocation.mkdir(); 
        if(!isCreated) { 
          //目標(biāo)上傳目錄創(chuàng)建失敗,可做其他處理,例如拋出自定義異常等,一般應(yīng)該不會(huì)出現(xiàn)這種情況。 
          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();
  }  

}


 

除了單圖上傳還有多圖上傳,原理都是一樣的

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;


/**
 * 多文件上傳
 */
public class FilesUploadAction extends ActionSupport {
     //上傳文件存放路徑  
     private final static String UPLOADDIR = "/upload";  
     //上傳文件集合  
     private List<File> file;  
     //上傳文件名集合  
     private List<String> fileFileName;  
     //上傳文件內(nèi)容類型集合  
     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;//上傳路徑
       for (int i = 0; i < file.size(); i++) {  
         //循環(huán)上傳每個(gè)文件  
         uploadFile(i); 
         webpath="upload/"+this.getFileFileName().get(i);
       }
       return "SUCCESS";
     } 
   
 
    
    //執(zhí)行上傳功能  
     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); 
         //此處也可以在應(yīng)用根目錄手動(dòng)建立目標(biāo)上傳目錄 
         if(!fileLocation.exists()){ 
           boolean isCreated = fileLocation.mkdir(); 
           if(!isCreated) { 
             //目標(biāo)上傳目錄創(chuàng)建失敗,可做其他處理,例如拋出自定義異常等,一般應(yīng)該不會(huì)出現(xiàn)這種情況。 
             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;  
       }  
     }
   }

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

  • log4j如何根據(jù)變量動(dòng)態(tài)生成文件名

    log4j如何根據(jù)變量動(dòng)態(tài)生成文件名

    這篇文章主要介紹了log4j如何根據(jù)變量動(dòng)態(tài)生成文件名方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java使用hutool實(shí)現(xiàn)文件大小的友好輸出

    Java使用hutool實(shí)現(xiàn)文件大小的友好輸出

    這篇文章主要為大家詳細(xì)介紹了Java如何使用hutool實(shí)現(xiàn)文件大小的友好輸出,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解下
    2023-11-11
  • java學(xué)習(xí)之JVM運(yùn)行時(shí)常量池理解

    java學(xué)習(xí)之JVM運(yùn)行時(shí)常量池理解

    這篇文章主要介紹了java學(xué)習(xí)之JVM運(yùn)行時(shí)常量池理解,對(duì)常量池的好處以及基本類型的包裝類常量池等作了簡(jiǎn)要分析,有需要的朋友可以借鑒參考下
    2021-09-09
  • Python如何使用@property @x.setter及@x.deleter

    Python如何使用@property @x.setter及@x.deleter

    這篇文章主要介紹了Python如何使用@property @x.setter及@x.deleter,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • SpringBoot實(shí)現(xiàn)Md5對(duì)數(shù)據(jù)庫(kù)數(shù)據(jù)加密的示例

    SpringBoot實(shí)現(xiàn)Md5對(duì)數(shù)據(jù)庫(kù)數(shù)據(jù)加密的示例

    本文主要介紹了SpringBoot實(shí)現(xiàn)Md5對(duì)數(shù)據(jù)庫(kù)數(shù)據(jù)加密的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • Java中dubbo+zookeeper微服務(wù)架構(gòu)簡(jiǎn)介

    Java中dubbo+zookeeper微服務(wù)架構(gòu)簡(jiǎn)介

    Apache Dubbo是一款高性能的 Java RPC 框架,這篇文章主要介紹了Java中dubbo+zookeeper微服務(wù)架構(gòu),需要的朋友可以參考下
    2021-09-09
  • 使用Mybatis-plus策略自動(dòng)更新數(shù)據(jù)庫(kù)時(shí)間失敗問(wèn)題解決

    使用Mybatis-plus策略自動(dòng)更新數(shù)據(jù)庫(kù)時(shí)間失敗問(wèn)題解決

    這篇文章主要介紹了使用Mybatis-plus策略自動(dòng)更新數(shù)據(jù)庫(kù)時(shí)間失敗問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • 聊聊spring繼承的問(wèn)題

    聊聊spring繼承的問(wèn)題

    這篇文章主要介紹了spring繼承的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 關(guān)于Spring源碼是如何解決Bean的循環(huán)依賴

    關(guān)于Spring源碼是如何解決Bean的循環(huán)依賴

    這篇文章主要介紹了關(guān)于Spring源碼是如何解決Bean的循環(huán)依賴,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • SpringBoot靜態(tài)資源及原理解析

    SpringBoot靜態(tài)資源及原理解析

    這篇文章主要介紹了SpringBoot靜態(tài)資源及原理解析,當(dāng)創(chuàng)建一個(gè)jar工程時(shí),想引入css等靜態(tài)資源時(shí),需要遵守SpringBoot的靜態(tài)資源映射關(guān)系,通過(guò)WebMvcAutoConfiguration查看靜態(tài)配置資源的規(guī)則,需要的朋友可以參考下
    2023-12-12

最新評(píng)論