Java 上传文件(图片)

本文与用的时候有改动,由于是直接在这该的,没有测试,可能会有错误,当然也可能没错^_^,网上上传文件的方法很多,本文也是参考而来,所以本文重点并不是方法,而是几个注意的地方,相信可以帮你理解这种文件上传的方法,好运...

 

JSP:

注意:form 中 enctype="multipart/form-data" 不能少

<form name="uploadForm" method="post" id="uploadForm" action="uploadFileAction.action"
            enctype="multipart/form-data" >

<input type="file" name="uploadFile" id="uploadFile" />

<input type="text" name="givenName" id="givenName" />      

<input type="button" name="uploadBtn" value="上传 " οnclick="submit()"  /> 

</form>

 

 

Action:

 private File uploadFile;
 private String fileName;

 private String givenName;

 get,set 方法略....

 注意:注意fileName的set方法,fileName并不是像givenName一样从JSP直接传递过来的,它的值是从uploadFile中获取来的

 public String getFileName() {
  return fileName;
 }

 中间是JSP中file控件的name,文件以form的形式提交给后台,文件名也包含在file文件中,这里就是从file中把文件名提取出来的方法

 public void setUploadFileFileName(String fileName) {
  this.fileName = fileName;
 }

 

 上传方法调用:

 初始化:

UploadImage ui = new UploadImage(uploadFile,fileName, serverURL,givenName);

根绝需要调用方法:

 ui.uploadFile();

 String ... = ui.get....

 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.struts2.ServletActionContext;

/**
 * Upload file Class
 *
 * @author 

 * @version 
 */
public class UploadFile {
 // 所上传的文件
 private File file;
 // 文件保存在服务器上的路径
 private String serverURL;
 // 所上传文件的原始名字,可以根据这个名字取得所上传文件的格式后缀(.jpg,.txt...)
 private String fileName;
 // 自己给所上传的文件命名
 private String givenName;
 // 构造方法,初始化
 public UploadFile(File file,String fileName, String serverURL,String givenName) {
  this.file = file;
  this.serverURL = serverURL;
  this.fileName = fileName;
  this.givenName = givenName;
 }

 public File getFile() {
  return file;
 }

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

 public String getServerURL() {
  return serverURL;
 }

 public void setServerURL(String serverURL) {
  this.serverURL = serverURL;
 }

 public String getFileName() {
  return fileName;
 }

 public void setFileName(String fileName) {
  this.fileName = fileName;
 }
 
 public String getGivenName() {
  return givenName;
 }

 public void setGivenName(String givenName) {
  this.givenName = givenName;
 }

 /**
  * upload to server from localhost
  * 真正的上传操作
  * @param src
  * @param dst
  */
 private static void copy(File src, File dst) {
  try {
   InputStream in = null;
   OutputStream out = null;
   try {
    in = new BufferedInputStream(new FileInputStream(src), 10000);
    out = new BufferedOutputStream(new FileOutputStream(dst), 10000);
    byte[] buffer = new byte[100];
    while (in.read(buffer) > 0) {
     out.write(buffer);
    }
   } finally {
    if (null != in) {
     in.close();
    }
    if (null != out) {
     out.close();
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * Get the file format(jpg,gif,bmp.....)
  * 获得一个文件的后缀
  * @param fileName
  * @return
  */
 public static String getExtention(String fileName) {
  int pos = fileName.lastIndexOf(".");
  return fileName.substring(pos);
 }

 /**
  * Get random number
  * 获得一个随机数字符串,用于生成默认文件名
  * @return
  */
 public static String getRandom() {
  String strInt = "";
  for (int i = 0; i < 5; i++) {
   Random random = new Random();
   strInt += String.valueOf(random.nextInt(10));
  }
  return strInt;
 }
 /**
  * 獲取真正存储的文件名
  *
  * @return 真正保存的文件名
  */
 public String getRealFileName(){
  String realFileName = null;
  // 當沒有給所要上傳的文件命名或者名字為空的時候,獲取一個默認的名字(日期字符串+隨機數+後綴)
  if(this.givenName==null||"".equals(this.givenName)){
   SimpleDateFormat gs = new SimpleDateFormat("yyyyMMddHHmmss");
   String time = gs.format(new Date());
   realFileName = time + getRandom() + getExtention(this.fileName);
   // 命名不为空的时候,就返回(命名+后缀)
  }else{
   realFileName = this.givenName + getExtention(this.fileName);
  }
  return realFileName;
 }

 /**
  * Upload Image method
  *
  * @return
  */
 public void uploadFile() throws Exception {
  try {
   File uploadFile = new File(this.getParentURL()+ this.getRealFileName());
   if(!uploadFile.exists()){
    copy(this.file, uploadFile);
   }
  } catch (Exception ex) {
   throw ex;
  }
 }
 /**
  * 获得所存储上传文件服务器路径
  * @return
  */
 public String getParentURL() {
  return ServletActionContext.getServletContext().getRealPath(
    this.serverURL)
    + "/";
 }

 /**
  * Delete Image
  * 上传文件到服务器有时候需要把旧的文件替换掉,这个方法就是把原来的旧文件删除
  * @param oldImg 原来文件的文件名
  * @return
  * @throws Exception
  */
 public boolean deleteImg(String oldImg) throws Exception {
  boolean bool = false;
  try {
   File oldFile = new File(this.getParentURL() + oldImg);
   if (oldFile.exists()) {
    bool = oldFile.delete();
   } else {
    bool = true;
   }
  } catch (Exception ex) {
    ex.printStackTrace();
    bool = false;
  }
  return bool;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值