在开发一些社交网站时,需要有允许用户上传自己本地文件的功能,则需要文件的上传下载代码。

首先考虑的是文件的储存位置,这里不考虑存在数据库,因为通过数据库查询获取十分消耗资源与时间,故需将数据存储在服务器上。

1. 前台页面的代码:

<form action="photo-up" method="post" enctype="multipart/form-data">
上传图片: <input type="file" name="myFile">
<!--或者<s:file name="myFile" label="FILE"/> --> <input type="submit" value="上传"/><s:fielderror id="error"/>
</form>
<s:file name="myFile" label="FILE"/>

上面的重要属性是name,要求如后台的文件定义名一样。

2. 文件上传后台代码(struts2的Action控制类):

public class PhotoAction extends ActionSupport {

    private static final long serialVersionUID = 6897968438458946989L;
   private File myFile;
private String myFileContentType;
private String myFileFileName;
//定义以上三个变量,myFile是接受前台的文件,要求名字与name属性一样,其他的见名知意(就当固定格式)
User user = (User)ActionContext.getContext().getSession().get("user") ; public String up() throws Exception {
//创建输入流
InputStream is = new FileInputStream(myFile) ;
//设置不同用户的文件保存目录
String photoPath = ServletActionContext.getServletContext()
.getRealPath("/user/photo/" + user.getUserName()) ;
File filePhotoPath = new File(photoPath);
if(!filePhotoPath.isDirectory()) {
filePhotoPath.mkdir();
}
//解决中文文件名问题,采用UUID获取随机字符串
String extension = FilenameUtils.getExtension(getMyFileFileName());//获取文件的拓展名
String filename = UUID.randomUUID().toString() + "."+ extension;
File toFile = new File(filePhotoPath, filename) ;
//输出流
OutputStream os = new FileOutputStream(toFile) ;
byte[] buf = new byte[1024] ;
int lenth ;
while((lenth = is.read(buf)) >0 ){
os.write(buf, 0, lenth);
}
is.close();
os.close();
return "up";
}
//属性的get、set方法
  public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
} }

此代码将文件存储在  (Web应用程序的根目录的绝对路径)/user/photo/(userName) 下面。

在struts.xml文件中配置文件限制要求:

<action name="photo-*" class="photoAction" method="{1}">

            <!-- 配置fileUpload拦截器 -->
<interceptor-ref name="fileUpload">
<!-- 配置允许上传文件类型 -->
<param name="allowedTypes">image/bmp,image/pjpeg,image/gif,image/png</param>
<!-- 配置允许上传文件大小最大值 -->
<param name="maximumSize">512000</param>
</interceptor-ref>
<result name="up" type="redirectAction">photo-showPhoto</result>
<result name="input" type="redirectAction">photo-showPhoto</result>
<result name="showPhoto">/showphoto.jsp</result>
</action>

3. 文件的下载代码

  文件的下载代码比较简单,只需要得到web应用程序目录下文件的所在位置即可,然后放在一个超链接里面点击就可以浏览或下载。

public String showPhoto(){
String photoPath = ServletActionContext.getServletContext()
.getRealPath("/user/photo/" + user.getUserName()) ;
File file = new File(photoPath) ;
    //获取该目录下所有的文件名
String[] photoList = file.list() ;
    //将获取文件名的集合放在request里
     ServletActionContext.getRequest().setAttribute("photoList", photoList);
return "showPhoto" ;
}

4. 返回页面,显示文件连接:

<table align="center" border="1" cellpadding="0" cellspacing="10">
<tr>
<s:iterator value="#request.photoList" var="photo" status="stu">
<td>
<a href='user/photo/${sessionScope.user.userName }/<s:property value="photo"/>'>
<img alt="" src='user/photo/${sessionScope.user.userName }/<s:property value="photo"/>'
width="100" height="120"></a>
</td>
<s:if test="(#stu.index + 1) % 6 == 0">
</tr>
<tr>
</s:if>
</s:iterator>
</tr>
</table>

以上有个在table里自动换行的小技巧,当(集合下标+1)能整除6就加</tr>结束一行,加<tr>开始新的一行。

最新文章

  1. c# winform 动态画矩形 矩形大小可以拖动
  2. 2016-09-19: linux后台运行
  3. webdriver 获取alert 提示no alert is active
  4. Android根据字符串加载Activity和图片
  5. android post带数据请求方式,传递的数据格式包括json和map
  6. 【BZOJ-1787&amp;1832】Meet紧急集合&amp;聚会 倍增LCA
  7. Jquery DOM元素的方法
  8. [转] Python 代码性能优化技巧
  9. Qt实现桌面动态背景雪花飘落程序
  10. (转)Linux SLUB 分配器详解
  11. Android常用ProgressDialog设置
  12. 在Maven的配置文件中,自定义私有仓库地址和设置下载的jar包的保存位置
  13. .NET MVC与三层架构
  14. emqx源码编译
  15. linux目录说明
  16. Windows 10 IoT Core 17101 for Insider 版本更新
  17. Empirical Evaluation of Speaker Adaptation on DNN based Acoustic Model
  18. ubuntu系统默认源更改为阿里源
  19. IdentityServer4关于多客户端和API的最佳实践【含多类型客户端和API资源,以及客户端分组实践】【下】
  20. throws和throw的区别

热门文章

  1. websocket 协议 使用
  2. vue computed 可以使用getter和setter
  3. dubbo初探(转载)
  4. PLSQL Split分割字符串
  5. 使用C#开发ActiveX控件[new]
  6. MySQL学习总结(二)数据库以及表的基本操作
  7. django-1.11.3 源码详解 -- 0001 django-admin.py 的调用逻辑
  8. vue组件调用(用npm安装)
  9. atitit.thumb生成高质量缩略图 php .net c++ java
  10. atitit.报表最佳实践oae 与报表引擎选型