SSH開發中的檔案上傳
阿新 • • 發佈:2018-12-09
檔案上傳的要素
- 表單提交方式必須是POST
- 表單的enctype屬性:必須設定為multipart/form-data
- 表單必須有檔案上傳項:file
表單
<form id=form1 name=form1 action="${pageContext.request.contextPath }/image_save.action" method=post enctype="multipart/form-data">
<input type="file" name="upload">
<input class=button id=sButton2 type=submit value="儲存" name=sButton2>
<form>
上傳中會出現的問題和解辦法
public class UploadUtils {
/*
* 解決目錄下檔名重複的問題
*/
public static String getUuidFileName(String filename) {
int idx = filename.lastIndexOf("."); //找到檔名中 . 所在的位置
String entions = filename.substring(idx); //獲得副檔名
String ufilename = UUID.randomUUID().toString().replace("-", "")+entions;
return ufilename;
}
/*
* 目錄分離
*/
public static String getPath(String uuidFilename){
int code1 = uuidFilename. hashCode();
int d1 = code1 & 0xf; //作為一級目錄
int code2 = code1 >>> 4; //右移4位
int d2 = code2 & 0xf; //作為二級目錄
return "/"+d1+"/"+d2;
//進行相同程式碼操作,可以一直分離下去
}
}
imageAction.class的編寫
public class imageAction{
public void image_save(){
//上傳圖片
if(upload != null){
//檔案的上傳:
//設定檔案上傳的路徑
String path ="C:/upload";
//一個目錄下存放相同的檔名:產生隨機檔名
String uuidFilename =UploadUtils.getUuidFileName(uploadFileName);
//一個目錄下存檔案太多:對檔案目錄進行分離
String realPath = UploadUtils.getPath(uuidFilename);
//建立目錄:
String url = path+realPath;
File file = new File(url);
if(!file.exists()){
file.mkdirs();
}
//檔案上傳
File dictFile = new File(url+"/"+uuidFilename);
FileUtils.copyFile(upload, dictFile);
//設定image屬性的值
customer.setCust_image(url+"/"+uuidFilename);
}
}
}
在struts配置檔案中進行配置
<package name="imagetest" extends="struts-default" namespace="/">
<action name="image_*" class="imageAction" method="{1}">
</action>
</package>
struts檔案上傳的注意事項
- struts中對上傳檔案的大小進行的初始設定
struts.multipart.maxSize=20697152
- 如果想改變大小,需要在struts的配置檔案中進行修改
- 這個的修改的是表單中上傳的檔案的總大小,如果想要規定單個檔案大小,需要使用攔截器
<!-- 配置Struts2表單中上傳的檔案的總大小 -->
<constant name="struts.multipart.maxSize" value="需要的大小"></constant>
- 設定單個檔案的大小
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">所需要設定的單個檔案大小</param>
<param name="fileUpload.allowedExtensions">允許上傳的檔案型別</param>
</interceptor-ref>