我们写项目的时候,上传图片与上传文件都是非常重要的一个代码,这关系到项目是否能计划诺入信息的关键,那我们下面就来讲一下strust2上传文件使用到的代码,还有代码的原理吧。
private String uploadContentType;
private String uploadFileName;
private String savepath;
private File upload;
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getSavepath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savepath);
}
public void setSavepath(String savepath) {
this.savepath = savepath;
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String execute() throws Exception {
Calendar now = Calendar.getInstance();
String path = getSavepath() + "/" + now.get(Calendar.YEAR) + "/"
+ (now.get(Calendar.MONTH) + 1);
path = StringsCommom.returnPath(path);
File file = new File(path);
if (!file.exists())
file.mkdirs();
FileOutputStream fos = new FileOutputStream(path + "\\"
+ StringsCommom.returnFileNewsName(getUploadFileName()));
FileInputStream fis = new FileInputStream(getUpload());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
fis.close();
return "success";
}
通过上面的代码我们可以看到我们主要是将流的信息放到文件里面去。
如有不懂,联系独占网络(http://www.sz886.com)