下载:
public class FunctionAct extends BaseAction implements ServletContextAware {
private String filename;
private String mimeType;
private java.io.InputStream inStream;
private ServletContext context;
public String function_down() throws Exception {
mimeType = context.getMimeType(filename);
return "down";
}
public InputStream getInStream() {
inStream = context.getResourceAsStream("/upload/" + filename);
if (inStream == null) {
inStream = new ByteArrayInputStream("Sorry,File not found !"
.getBytes());
}
return inStream;
}
public String getMimeType() {
return mimeType;
}
public void setFilename(String filename) {
try {
this.filename = new String(filename.getBytes("ISO8859-1"), "GBK");
} catch (UnsupportedEncodingException e) {
}
}
public String getFilename() {
try {
return new String(filename.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
return this.filename;
}
}
public void setServletContext(ServletContext context) {
this.context = context;
}
<result type="stream" name="down">
<param name="contentType">${mimeType}</param>
<param name="inputName">inStream</param>
<param name="contentDisposition">attachment;filename="${filename}"</param>
</result>
http://localhost:8080/bs0514/admin/function/function_down.do?filename=ms.txt
上传:
1.设置 enctype="multipart/form-data"
<form action="<%=path%>/strutsUpload.do" method="post" enctype="multipart/form-data">
<input type="file" name="uploadImage" >
<input type="submit" value="submit"/>
</form>
2.在action中添加属性,注意红色字体
private java.io.File uploadImage ;
private java.lang.String uploadImageContentType;
private java.lang.String uploadImageFileName ;
String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
java.io.File file = new java.io.File(realPath);
if(!file.exists())
file.mkdirs();
FileUtils.copyFile(uploadImage, new java.io.File(file,uploadImageFileName)) ;
当然这里路径需要再改成自己的路径。
如果文件有限制,则可加上限制文件大小
<constant name="struts.multipart.maxSize" value="10701096"></constant>
多文件上传也一样
<input type="file" name="uploadImage" >
<input type="file" name="uploadImage" >
String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
java.io.File file = new java.io.File(realPath);
if(!file.exists())
file.mkdirs();
// FileUtils.copyFile(uploadImage, new java.io.File(file,uploadImageFileName)) ;
for(int i = 0 ;i<uploadImages.length;i++)
{
java.io.File uploadImage = uploadImages[i];
FileUtils.copyFile(uploadImage, new java.io.File(file,uploadImageFileNames[i])) ;
}