struts1.2文件上传
jsp頁面
?
<!--上傳圖片時,在當前頁面顯示圖片 注意form中必須加 enctype="multipart/form-data"-->
<form action="XXX.do"?enctype="multipart/form-data">
<input type="file" name="file" onpropertychange="document.all.imgBook.src='file:///'+this.value" />
??? ?<div id="img">
??? ??<img id="imgBook" style="WIDTH: 110px; HEIGHT: 154px" height="154" src="" width="110"/>
??? ?</div>?
</form>
ActionForm
public class DownloadForm extends ActionForm {
?private String fileName;
?
?private FormFile file;
public FormFile getFile() {
??return file;
?}
?public void setFile(FormFile file) {
??this.file = file;
?}
?public String getFileName() {
??return fileName;
?}
?public void setFileName(String fileName) {
??this.fileName = fileName;
?}
}
?
Action
public class Download_AddAction extends Action {
?public ActionForward execute(ActionMapping mapping, ActionForm form,
???HttpServletRequest request, HttpServletResponse response) {
??DownloadForm downloadForm = (DownloadForm) form;// TODO Auto-generated method stub
??
//??上傳
????FormFile file = downloadForm.getFile();
????? //根據時間設置文件名
????Calendar calendar=Calendar.getInstance();
??? ????String time=calendar.get(Calendar.YEAR)+""+calendar.get(Calendar.DAY_OF_YEAR)+""+calendar.getTimeInMillis();
??? ????String fileName = time+file.getFileName();
????InputStream streamIn = null; //輸入輸出流
????OutputStream streamOut = null;
????String sysroot = servlet.getServletContext().getRealPath("/download/upload"); //獲取圖片文件夾路徑????
????String filePath = sysroot + "//" + fName; //最終路徑
????try {
?????streamIn = file.getInputStream(); //以下是上傳的代碼,不用變,固定的
?????streamOut = new FileOutputStream(filePath);
?????int bytesRead = 0;
?????byte[] buffer = new byte[20480];
?????while ( (bytesRead = streamIn.read(buffer, 0, 20480)) != -1) {
?????streamOut.write(buffer, 0, bytesRead);
?????}
?????streamOut.close();
?????streamIn.close();
????request.setAttribute("info", "上傳成功啦");
???
?????}
?????catch (FileNotFoundException e) {
?????request.setAttribute("error", "上傳失敗啦");
?????e.printStackTrace();
?????return mapping.findForward("jumpErrorPage");
?????}
?????catch (IOException e) {
?????request.setAttribute("error", "上傳失敗啦");
?????e.printStackTrace();
?????return mapping.findForward("jumpErrorPage");
?????}
?
?return mapping.findForward("jumpSuccessPage");
}
總結
以上是生活随笔為你收集整理的struts1.2文件上传的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使表格中的文字自动换行
- 下一篇: 上传自动显示图片 代码