一.提交表單的<form> method屬性必須為post 並且添加enctype="multipart/form-data" 屬性
前台:
<td>上傳資質:</td> <td> <input type="file" name="upload"> </td>
UploadUtils工具類
package com.home.utils;
import java.util.UUID;
/**
* 文件上床的工具類
* @author Administrator
*
*/
public class UploadUtils {
/**
* 傳入文件名稱,返回唯一的名稱
* @param filename
* @return
*/
public static String getUUIDName(String filename){
//先查找 從后往前找
int index = filename.lastIndexOf(".");
//截取后綴名
String lastname = filename.substring(index,filename.length());
//System.out.println(filename);
//唯一字符串
String uuid = UUID.randomUUID().toString().replace("-", "");//默認帶有-
return uuid+lastname;
}
public static void main(String[] args) {
String filename = "gril.jsp";
System.out.println(getUUIDName(filename));
}
}
domain等文件中添加文件上傳路徑屬性
WEB層代碼(連同增加客戶一起)
/**
* 文件上傳,需要在Action類中定義成員的屬性,命名是有規則的!!
* private File upload; //表示要上傳的文件(與前台name一致) io包的File類
* private String uploadFileName; //表示上傳文件的名稱(沒有中文亂碼--已解決)
* private String uploadContentType;//表示上傳文件的MIME類型
* 提供set方法,攔截器就注入值了
*/
private File upload;
private String uploadFileName;
private String uploadContentType;
public void setUpload(File upload) {
this.upload = upload;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String save() throws IOException{
//做文件的上傳,說明用戶選擇了上傳的文件
if (uploadFileName!=null) {
//打印
//System.out.println("文件名稱:"+uploadFileName);
System.out.println("文件類型:"+uploadContentType);
//把名稱處理一下
String uuidname = UploadUtils.getUUIDName(uploadFileName);
//把文件上傳到D:\\Tomcat8.0\\webapps\\upload
String path = "D:\\Tomcat8.0\\webapps\\upload\\";
//創建file對象
File file = new File(path+uuidname);
//簡單方式
FileUtils.copyFile(upload, file);//導org.apache.commons.io的包
//把文件上傳的路徑,保存到客戶表中
customer.setFilepath(path+uuidname);
}
customerService.save(customer);
return "save";
}
**注
1.文件大小非常有限(默認2097152為2M),可以自行設置
在struts.xml文件中添加
<!-- 設置上傳文件總大小 --> <constant name="struts.multipart.maxSize" value="20971520"></constant>
2.也可以設置允許的擴展名
在struts.xml文件中的上傳文件action標簽中添加
<!-- 引入默認攔截器 --> <interceptor-ref name="defaultStack"> <!-- 決定上傳文件的類型 --> <param name="fileUpload.allowedExtensions">.jpg,.txt</param> </interceptor-ref>
