搜尋
首頁Javajava教程java web圖片上傳和文件上傳

图片上传和文件上传本质上是一样的,图片本身也是文件。文件上传就是将图片上传到服务器,方式虽然有很多,但底层的实现都是文件的读写操作。

注意事项

1.form表单一定要写属性enctype="multipart/form-data"

2.为了能保证文件能上传成功file控件的name属性值要和你提交的控制层变量名一致,

例如空间名是file那么你要在后台这样定义

private File file; //file控件名

private String fileContentType;//图片类型

private String fileFileName; //文件名

 

jsp页面

<%@ 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>

页面数据需要提交的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");//图片要上传到的服务器路径
        String names[]=fileFileName.split("\\.");
        String fileName="";
        if(names.length>=1){
            fileName=getRandomString(20)+"."+names[names.length-1];
        }
        String picPath="upload/"+fileName;//图片保存到数据库的路径
        File file1=new File(root);
        try {
            FileUtils.copyFile(file, new File(file1,fileName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }
    
    /*获取一条随机字符串*/
    public String getRandomString(int length) { //length表示生成字符串的长度  
        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();     
     }    

}

这是通过复制的方式上传文件,还有其他方式

方法二

@Controller("contractAction")
public class ContractAction extends ActionSupport {
    
    private final static String UPLOADDIR = "/files";//文件上传的路径,在webContent下建立
    private File file;  //input控件名一定为file 
    //上传文件名集合   
    private String fileFileName;   
    //上传文件内容类型集合   
    private String fileContentType; 
    
    private String filename;
 
    public String upload() throws FileNotFoundException, IOException{
        String path=uploadFile();//文件保存数据库的路径
    
        return SUCCESS;
    }
    
    //执行上传功能   
    @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);  
            //此处也可以在应用根目录手动建立目标上传目录  
            if(!fileLocation.exists()){  
                boolean isCreated  = fileLocation.mkdir();  
                if(!isCreated) {  
                    //目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。  
                    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;   
         //上传文件内容类型集合   
         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++) {   
                 //循环上传每个文件   
                 uploadFile(i); 
                 webpath="upload/"+this.getFileFileName().get(i);
             }
             return "SUCCESS";
         }  
      
  
       
        //执行上传功能   
         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);  
                 //此处也可以在应用根目录手动建立目标上传目录  
                 if(!fileLocation.exists()){  
                     boolean isCreated  = fileLocation.mkdir();  
                     if(!isCreated) {  
                         //目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。  
                         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;   
             }   
         }
     }


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JVM如何在不同平台上管理垃圾收集?JVM如何在不同平台上管理垃圾收集?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

為什麼Java代碼可以在不同的操作系統上運行,而無需修改?為什麼Java代碼可以在不同的操作系統上運行,而無需修改?Apr 28, 2025 am 12:14 AM

Java代碼可以在不同操作系統上無需修改即可運行,這是因為Java的“一次編寫,到處運行”哲學,由Java虛擬機(JVM)實現。 JVM作為編譯後的Java字節碼與操作系統之間的中介,將字節碼翻譯成特定機器指令,確保程序在任何安裝了JVM的平台上都能獨立運行。

描述編譯和執行Java程序的過程,突出平台獨立性。描述編譯和執行Java程序的過程,突出平台獨立性。Apr 28, 2025 am 12:08 AM

Java程序的編譯和執行通過字節碼和JVM實現平台獨立性。 1)編寫Java源碼並編譯成字節碼。 2)使用JVM在任何平台上執行字節碼,確保代碼的跨平台運行。

基礎硬件架構如何影響Java的性能?基礎硬件架構如何影響Java的性能?Apr 28, 2025 am 12:05 AM

Java性能与硬件架构密切相关,理解这种关系可以显著提升编程能力。1)JVM通过JIT编译将Java字节码转换为机器指令,受CPU架构影响。2)内存管理和垃圾回收受RAM和内存总线速度影响。3)缓存和分支预测优化Java代码执行。4)多线程和并行处理在多核系统上提升性能。

解釋為什麼本地庫可以破壞Java的平台獨立性。解釋為什麼本地庫可以破壞Java的平台獨立性。Apr 28, 2025 am 12:02 AM

使用原生庫會破壞Java的平台獨立性,因為這些庫需要為每個操作系統單獨編譯。 1)原生庫通過JNI與Java交互,提供Java無法直接實現的功能。 2)使用原生庫增加了項目複雜性,需要為不同平台管理庫文件。 3)雖然原生庫能提高性能,但應謹慎使用並進行跨平台測試。

JVM如何處理操作系統API的差異?JVM如何處理操作系統API的差異?Apr 27, 2025 am 12:18 AM

JVM通過JavaNativeInterface(JNI)和Java標準庫處理操作系統API差異:1.JNI允許Java代碼調用本地代碼,直接與操作系統API交互。 2.Java標準庫提供統一API,內部映射到不同操作系統API,確保代碼跨平台運行。

Java 9影響平台獨立性中引入的模塊化如何?Java 9影響平台獨立性中引入的模塊化如何?Apr 27, 2025 am 12:15 AM

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

什麼是字節碼,它與Java的平台獨立性有何關係?什麼是字節碼,它與Java的平台獨立性有何關係?Apr 27, 2025 am 12:06 AM

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器