struts1.2文件上传

jsp页面


<form action="XXX.do">
<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");
}

你可能感兴趣的:(jsp,servlet)