struts2圖片上傳顯示圖片
A. struts2文件上傳中,如何限制上傳的文件類型
只需要在struts配置文件中配置就OK了
案例如下:
<package name="upload" extends="struts-default" namespace="/upload">
<!-- 配置 -->
<action name="upload" class="www.ijava.com.UploadAction" >
<param name="savePath">e:/images/</param>
<!--往fileuploadInterceptor 注入 -->
<interceptor-ref name="defaultStack">
<!-- 改變當前文件運行上傳的類型 -->
<param name="fileUpload.allowedTypes">image/jpeg,image/jpg</param>
<!-- 允許的文件後綴 -->
<param name="fileUpload.allowedExtensions">jpg,jpeg,gif</param>
</interceptor-ref>
<result>/index.jsp</result>
</action>
B. struts2上傳圖片到linux伺服器,成功上傳文件,無法返迴路徑,報錯: net::ERR_CONTENT_LENGTH_MISMATCH
因為windows和linux系統的文件路徑分割符是不一樣的。一個是「/」一個是「\」,所以換了環境當熱會錯。java中有一個方法叫做File.separator可以得到是運行環境下的分隔符,你需要在代碼中做出修改。將文件路徑拆開後然後使用 File.separator拼接。
C. SSH2框架圖片上傳到資料庫並顯示在JSP頁面
//傳統的struts2上傳是很簡單的。
//頁面form提交到action:
//這里使用集合,頁面提交過來的n個inputname=「file」的文件將會被裝進去,如果只上傳一
//個文件可以直接聲明成:privateFilefile、StringfileFileName、StringfileContentType
privateList<File>file;
privateList<String>fileFileName;
privateList<String>fileContentType;
publicList<File>getFile(){
returnfile;
}
publicvoidsetFile(List<File>file){
this.file=file;
}
publicList<String>getFileFileName(){
returnfileFileName;
}
publicvoidsetFileFileName(List<String>fileFileName){
this.fileFileName=fileFileName;
}
publicList<String>getFileContentType(){
returnfileContentType;
}
publicvoidsetFileContentType(List<String>fileContentType){
this.fileContentType=fileContentType;
}
publicStringexecute()throwsException{
List<String>s=newArrayList<String>();
for(inti=0;i<file.size();i++){
InputStreamis=newFileInputStream(file.get(i));
//在webroot先建立個upload文件夾,也可以用代碼創建,這里為了簡便,就直接使用了
Stringroot=ServletActionContext.getRequest().getRealPath("/upload");
FiledistFile=newFile(root,this.getFileFileName().get(i));
OutputStreamos=newFileOutputStream(distFile);
byte[]buffer=newbyte[400];
intlength=0;
while((length=is.read(buffer))>0){
os.write(buffer,0,length);
}
is.close();
os.close();
//資料庫存放以下路徑,當需要在頁面顯示,直接提取出來用IMG標簽裝載即可
StringnewFilePath=root+"/"+distFile.getFileName();
}
returnSUCCESS;
}
//的代碼不需要很復雜,簡單的執行資料庫插入就好。