Iframe仿Ajax非同期アップロードファイル(写真)
JSP:
FileコントロールimgFileがファイルを選択した時にこのイベントをトリガします。manFormはフォームアップロード画像を提出しました。結果(アップロード成功した画像表示、失敗メッセージ)はimgIframeに表示されます。imgFrame以外のページは更新しなくてもいいので、Ajaxのような効果があります。
ここで使うのはstruts 2です。
まとめ:
主なFormアップロードファイルを提出した結果、メインFormの中のIframeに表示されます。このようにページ全体を更新する必要はなく、Ajaxのような効果を達成します。
JS:FileコントロールimgFileがファイルを選択した時にこのイベントをトリガします。manFormはフォームアップロード画像を提出しました。結果(アップロード成功した画像表示、失敗メッセージ)はimgIframeに表示されます。imgFrame以外のページは更新しなくてもいいので、Ajaxのような効果があります。
$(document).ready(function(){
$("#imgFile").bind("change",function(){
document.getElementById("mainForm").action="FileAction!uploadImage.action";
document.getElementById("mainFormrm").target = "imgIframe";
document.getElementById("mainFormrm").submit();
});
});
FileActionuploadImage.action:ここで使うのはstruts 2です。
public class FileAction{
//
private File imgFile;
//
private String imgFileContentType;
//
private String imgFileFileName;
//get,set ...
/**
*
* @return
*/
public String uploadImage(){
//
String realPath = "/var/www/upload";
// realPath url
String url = "http://www.myimg.com";
String image_url = "";
try {
int m = this.getImgFileFileName().lastIndexOf(".");
String imgType = this.getImgFileFileName().substring(m+1,this.getImgFileFileName().length()).toLowerCase();
if(!"#jpg#jpeg#gif#png#bmp#icon#".contains(("#"+imgType+"#"))){
this.request.setAttribute("err_msg"," jpg|jpeg|gif|png|bmp|icon !"+image_url);
return "upload_image";
}
// myFile
InputStream is = new FileInputStream(imgFile);
int the_size = 50;
// (k)
int size = is.available()/1024;
if(size>the_size){
this.request.setAttribute("err_msg"," ("+String.valueOf(the_size)+"k )!"+image_url);
return "upload_image";
}
String newFileName = "new_imag"+"."+imgType;
// ,
File dir = new File(realPath);
if(!dir.exists()){
dir.mkdirs();
}
//
File toFile = new File(realPath, newFileName);
image_url = url + File.separator + newFileName;
//
OutputStream os;
os = new FileOutputStream(toFile);
//
byte[] buffer = new byte[1024];
int length = 0;
// myFile toFile
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
//
is.close();
//
os.close();
} catch (Exception e) {
this.request.setAttribute("err_msg"," !");
return "upload_image";
}
this.request.setAttribute("url",image_url);
return "upload_image";
}
}
結果(url,errg)はupload_に表示されます。イメージ.jspの中で、どうやって分かりますか?まとめ:
主なFormアップロードファイルを提出した結果、メインFormの中のIframeに表示されます。このようにページ全体を更新する必要はなく、Ajaxのような効果を達成します。