服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java实现简单图片上传下载功能

java实现简单图片上传下载功能

2021-06-04 13:50二营长1 Java教程

这篇文章主要为大家详细介绍了java实现简单图片上传下载功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java实现简单图片上传下载的具体代码,供大家参考,具体内容如下

1.首先在上传图片界面:将form表单的enctype改为:multipart/form-data

2.定义一个实体类用来将存放图片存放的路径存入到mysql中private string imgpath;

3.在spring容器中注入处理图片的解析器

?
1
2
3
4
5
6
<bean name="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver">
 <!-- 设置默认编码 -->
    <property name="defaultencoding" value="utf-8"></property>
    <!-- 上传图片最大大小5m--> 
    <property name="maxuploadsize" value="5242440"></property>
</bean>

4.在controller层接收的时候需要用 @requestparam("file") commonsmultipartfile file来接收,如果是多个图片就是@requestparam("file") commonsmultipartfile[] files来接收

5.通过工具类处理返回要存入实体类的图片的路径

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
public class fileuputil {
 
 /**
 * 上传多个文件或图片上传在项目路径下的img文件夹在
 * !!!!!!重新部署项目实效,因为文件夹被删除
 * @param files
 * @param request
 * @return
 */
 public static list<string> upfiles(commonsmultipartfile files[],httpservletrequest request){
  list<string> list = new arraylist<string>();
     // 获得项目的路径
     servletcontext sc = request.getsession().getservletcontext();
     // 上传位置
     string path = sc.getrealpath("/img") + file.separatorchar; // 设定文件保存的目录
     file f = new file(path);
     if (!f.exists())
       f.mkdirs();
    
     for (int i = 0; i < files.length; i++) {
       // 获得原始文件名
       string filename = files[i].getoriginalfilename();
       system.out.println("原始文件名:" + filename);
       // 新文件名
       string newfilename = uuid.randomuuid() + filename;
       if (!files[i].isempty()) {
         try {
           fileoutputstream fos = new fileoutputstream(path
               + newfilename);
           inputstream in = files[i].getinputstream();
           int b = 0;
           while ((b = in.read()) != -1) {
             fos.write(b);
           }
           fos.close();
           in.close();
         } catch (exception e) {
           e.printstacktrace();
         }
       }
       system.out.println("上传图片到:" + path + newfilename);
       list.add("img/"+newfilename);
     }
     return list;
 }
 /**
 * 上传一个文件或图片
 * 上传多个文件或图片上传在项目路径下的img文件夹在
 * !!!!!!重新部署项目实效,因为文件夹被删除
 * @param file
 * @param request
 * @return
 */
 public static string upfile(commonsmultipartfile file,httpservletrequest request){
  // 获得项目的路径
    servletcontext sc = request.getsession().getservletcontext();
    // 上传位置
    string path = sc.getrealpath("/img") + file.separatorchar; // 设定文件保存的目录
    file f = new file(path);
    if (!f.exists())
      f.mkdirs();
      // 获得原始文件名
      string filename = file.getoriginalfilename();
      system.out.println("原始文件名:" + filename);
      // 新文件名
      string newfilename = uuid.randomuuid() + filename;
      if (!file.isempty()) {
        try {
          fileoutputstream fos = new fileoutputstream(path
              + newfilename);
          inputstream in = file.getinputstream();
          int b = 0;
          while ((b = in.read()) != -1) {
            fos.write(b);
          }
          fos.close();
          in.close();
        } catch (exception e) {
          e.printstacktrace();
        }
      }
      system.out.println("上传图片到:" + path + newfilename);
      return "img/"+newfilename;
 }
 
 /**
 * 下载
 * @param request
 * @param response
 * @param filename
 * @return
 */
 public static void downfile(httpservletrequest request,
      httpservletresponse response,string filename) {
    // 得到要下载的文件名
    string filename = filename.substring(4);
    try {
      filename = new string(filename.getbytes("iso8859-1"), "utf-8");
      // 获取上传文件的目录
      servletcontext sc = request.getsession().getservletcontext();
      // 上传位置
      string filesaverootpath = sc.getrealpath("/img"); 
       
      system.out.println(filesaverootpath + "\\" + filename);
      // 得到要下载的文件
      file file = new file(filesaverootpath + "\\" + filename);
       
      // 如果文件不存在
      if (!file.exists()) {
        request.setattribute("message", "您要下载的资源已被删除!!");
        system.out.println("您要下载的资源已被删除!!");
        return ;
      }
      // 处理文件名
      string realname = filename.substring(filename.indexof("_") + 1);
      // 设置响应头,控制浏览器下载该文件
      response.setheader("content-disposition", "attachment;filename="
          + urlencoder.encode(realname, "utf-8"));
      // 读取要下载的文件,保存到文件输入流
      fileinputstream in = new fileinputstream(filesaverootpath + "\\" + filename);
      // 创建输出流
      outputstream out = response.getoutputstream();
      // 创建缓冲区
      byte buffer[] = new byte[1024];
      int len = 0;
      // 循环将输入流中的内容读取到缓冲区当中
      while ((len = in.read(buffer)) > 0) {
        // 输出缓冲区的内容到浏览器,实现文件下载
        out.write(buffer, 0, len);
      }
      // 关闭文件输入流
      in.close();
      // 关闭输出流
      out.close();
    } catch (exception e) {
    }
  }
}

6.存入之后在jsp页面通过img标签显示<img alt="img" src="//数据库中存入的路径"  width="100">

7.下载就是将图片的路径传入controller层中一个方法,调用工具类中的downfile方法,就可以了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_41950069/article/details/81354884

延伸 · 阅读

精彩推荐