SpringBoot:文件上传接收&&http图片获取

SpringBoot:文件上传接收&&http图片获取

application.yml

1
2
3
4
5
upload:
filePath: D:/test/
serviceIP: 127.0.0.1
servicePort: 8090
rootPath: D:\

FileController

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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package com.fufu.controller;

import com.fufu.service.FileService;
import com.fufu.tools.FileTypeUtil;
import com.fufu.tools.HttpClient;
import com.fufu.tools.UrlUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/test1")
public class FileController {
private static final Logger log = LoggerFactory.getLogger(FileController.class);
@Value("${upload.filePath}")
private String filePath;
@Value("${serviceIP}")
private String serviceIP;
@Value("${servicePort}")
private String servicePort;
@Value("${rootPath}")
private String rootPath;
@Autowired FileService fileService;
//接收单个file
@PostMapping("/test/upload1")
public Map<String, String> upload1(@RequestParam("file") MultipartFile file) throws IOException {
log.info("[文件类型] - [{}]", file.getContentType());
log.info("[文件名称] - [{}]", file.getOriginalFilename());
log.info("[文件大小] - [{}]", file.getSize());
try {
file.transferTo(new File(filePath + file.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
Map<String, String> result = new HashMap<>(16);
result.put("contentType", file.getContentType());
result.put("fileName", file.getOriginalFilename());
result.put("fileSize", file.getSize() + "");
return result;
}

//接收多个file
@PostMapping("/test/upload2")
public List<Map<String, String>> upload2(@RequestParam("file") MultipartFile[] files) throws IOException {
if (files == null || files.length == 0) {
return null;
}
List<Map<String, String>> results = new ArrayList<>();
for (MultipartFile file : files) {
file.transferTo(new File(filePath + file.getOriginalFilename()));
Map<String, String> map = new HashMap<>(16);
map.put("contentType", file.getContentType());
map.put("fileName", file.getOriginalFilename());
map.put("fileSize", file.getSize() + "");
results.add(map);
}
return results;
}

//接收base64图片字符串
@RequestMapping("/test/upload3")
public void upload2(String base64) throws IOException {
final File tempFile = new File(filePath+"upload3.jpg");
//防止有的没传 data:image/jpeg;base64, 的情况
String[] d = base64.split("base64,");
final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]);
FileCopyUtils.copy(bytes, tempFile);

}

//根据http协议下载图片
@RequestMapping("/test/upload4")
public String downloadFileByURL(String urlStr) throws IOException {
URL url = new URL(UrlUtil.toUtf8String(urlStr));
String picPath = filePath+"upload4.jpg";
File file = new File(picPath);
// 打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式为"GET"
conn.setRequestMethod("GET");
// 超时响应时间为5秒
conn.setConnectTimeout(5 * 1000);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");

// 通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 创建一个Buffer字符串
byte[] buffer = new byte[1024];
// 每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
// 使用一个输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer)) != -1) {
// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 关闭输入流
inStream.close();
// 创建输出流
FileOutputStream outStream2 = new FileOutputStream(file);
// 写入数据
outStream2.write(outStream.toByteArray());
// 关闭输出流
outStream2.close();

return picPath;
}

//实现从本地取图片上传到对应服务器上
@GetMapping(value="/uploadLocalFile")
public void uploadLocalFile(){
String relativePath = "test/haha.jpg";
String picUrl = null;
try {
picUrl = HttpClient.getInstance().uploadFileImpl("http://"+serviceIP+":"+servicePort+"/test1/uploadFile", rootPath + relativePath, "aTestFileName", null);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("-----picUrl:"+picUrl+"-----");
}

/**
* 单个文件上传
* @param file
* @param folder 文件夹根据上传文件type自动生成
* @param id
* @param request
* @return
* @throws ServletException
* @throws IOException
*/
@ApiOperation(value = "单个文件上传", notes= "根据type值将所上传图片分文件夹存放,如type=我是一个莫得感情的文件夹,文件路径将为“/我是一个莫得感情的文件夹/20181111/110.jpg”")
@PostMapping(value="/uploadFile")
public @ResponseBody String uploadFile( MultipartFile file, @RequestParam(defaultValue = "Common") String type, HttpServletRequest request) throws IOException, ServletException {
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
String relativePath = null;
String finalName = null;
if(file != null) {
String fileName = file.getOriginalFilename();
//获取文件后缀名
String ext= FileTypeUtil.getFileSuffix(fileName);
if(!"jpg".equalsIgnoreCase(ext)&& !"png".equalsIgnoreCase(ext)&& !"bmp".equalsIgnoreCase(ext) && !"jpeg".equalsIgnoreCase(ext))
return "上传的图片文件格式不正确";
relativePath = type + "/" + sf.format(new Date()) +"/";
String finalPath = filePath + relativePath;
try {
finalName = new Random().nextInt(999999) + "."+ ext;
String fullPath = fileService.uploadFile(file.getBytes(), finalPath, finalName);
if(fullPath.isEmpty()) {
return null;
}
}catch (Exception e) {
e.printStackTrace();
return "uploadimg failure: " + e.getMessage();
}
}else {
Collection<Part> parts = request.getParts();
for (Iterator<Part> iterator = parts.iterator(); iterator.hasNext();) {
Part part = iterator.next();
finalName = part.getSubmittedFileName();
relativePath = part.getName() + "/" + sf.format(new Date()) + "/";
String finalPath = filePath + relativePath;
fileService.uploadFile(part.getInputStream(), finalPath, finalName);
}
}
return relativePath + finalName;
}
}

HttpClient

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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package com.fufu.tools;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* HttpClient
*/
public class HttpClient {

/**
* 最大线程池
*/
public static final int THREAD_POOL_SIZE = 5;

public interface HttpClientDownLoadProgress {
public void onProgress(int progress);
}

private static HttpClient httpClientDownload;

private ExecutorService downloadExcutorService;

private HttpClient() {
downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
}

public static HttpClient getInstance() {
if (httpClientDownload == null) {
httpClientDownload = new HttpClient();
}
return httpClientDownload;
}

/**
* 下载文件
*
* @param url
* @param filePath
*/
public void download(final String url, final String filePath) {
downloadExcutorService.execute(new Runnable() {

@Override
public void run() {
httpDownloadFile(url, filePath, null, null);
}
});
}

/**
* 下载文件
*
* @param url
* @param filePath
* @param progress
* 进度回调
*/
public void download(final String url, final String filePath,
final HttpClientDownLoadProgress progress) {
downloadExcutorService.execute(new Runnable() {

@Override
public void run() {
httpDownloadFile(url, filePath, progress, null);
}
});
}

/**
* 下载文件
*
* @param url
* @param filePath
*/
private void httpDownloadFile(String url, String filePath,
HttpClientDownLoadProgress progress, Map<String, String> headMap) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
setGetHead(httpGet, headMap);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println(response1.getStatusLine());
HttpEntity httpEntity = response1.getEntity();
long contentLength = httpEntity.getContentLength();
InputStream is = httpEntity.getContent();
// 根据InputStream 下载文件
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int r = 0;
long totalRead = 0;
while ((r = is.read(buffer)) > 0) {
output.write(buffer, 0, r);
totalRead += r;
if (progress != null) {// 回调进度
progress.onProgress((int) (totalRead * 100 / contentLength));
}
}
FileOutputStream fos = new FileOutputStream(filePath);
output.writeTo(fos);
output.flush();
output.close();
fos.close();
EntityUtils.consume(httpEntity);
} finally {
response1.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* get请求
*
* @param url
* @return
*/
public String httpGet(String url) {
return httpGet(url, null);
}

/**
* http get请求
*
* @param url
* @return
*/
public String httpGet(String url, Map<String, String> headMap) {
String responseContent = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
setGetHead(httpGet, headMap);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity = response1.getEntity();
responseContent = getRespString(entity);
System.out.println("debug:" + responseContent);
EntityUtils.consume(entity);
} finally {
response1.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}

public String httpPost(String url, Map<String, String> paramsMap) {
return httpPost(url, paramsMap, null);
}

/**
* http的post请求
*
* @param url
* @param paramsMap
* @return
*/
public String httpPost(String url, Map<String, String> paramsMap,
Map<String, String> headMap) {
String responseContent = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
setPostHead(httpPost, headMap);
setPostParams(httpPost, paramsMap);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
responseContent = getRespString(entity);
EntityUtils.consume(entity);
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("responseContent = " + responseContent);
return responseContent;
}

/**
* 设置POST的参数
*
* @param httpPost
* @param paramsMap
* @throws Exception
*/
private void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)
throws Exception {
if (paramsMap != null && paramsMap.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = paramsMap.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
}
}

/**
* 设置http的HEAD
*
* @param httpPost
* @param headMap
*/
private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
if (headMap != null && headMap.size() > 0) {
Set<String> keySet = headMap.keySet();
for (String key : keySet) {
httpPost.addHeader(key, headMap.get(key));
}
}
}

/**
* 设置http的HEAD
*
* @param httpGet
* @param headMap
*/
private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
if (headMap != null && headMap.size() > 0) {
Set<String> keySet = headMap.keySet();
for (String key : keySet) {
httpGet.addHeader(key, headMap.get(key));
}
}
}

/**
* 上传文件
*
* @param serverUrl
* 服务器地址
* @param localFilePath
* 本地文件路径
* @param serverFieldName
* @param params
* @return
* @throws Exception
*/
public String uploadFileImpl(String serverUrl, String localFilePath,
String serverFieldName, Map<String, String> params)
throws Exception {
String respStr = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(serverUrl);
FileBody binFileBody = new FileBody(new File(localFilePath));

MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder
.create();
// add the file params
multipartEntityBuilder.addPart(serverFieldName, binFileBody);
// 设置上传的其他参数
setUploadParams(multipartEntityBuilder, params);

HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);

CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
respStr = getRespString(resEntity);
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
System.out.println("resp=" + respStr);
return respStr;
}

/**
* 设置上传文件时所附带的其他参数
*
* @param multipartEntityBuilder
* @param params
*/
private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
Map<String, String> params) {
if (params != null && params.size() > 0) {
Set<String> keys = params.keySet();
for (String key : keys) {
multipartEntityBuilder
.addPart(key, new StringBody(params.get(key),
ContentType.TEXT_PLAIN));
}
}
}

/**
* 将返回结果转化为String
*
* @param entity
* @return
* @throws Exception
*/
private String getRespString(HttpEntity entity) throws Exception {
if (entity == null) {
return null;
}
InputStream is = entity.getContent();
StringBuffer strBuf = new StringBuffer();
byte[] buffer = new byte[4096];
int r = 0;
while ((r = is.read(buffer)) > 0) {
strBuf.append(new String(buffer, 0, r, "UTF-8"));
}
return strBuf.toString();
}
}

FileService

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
package com.fufu.service;

import com.fufu.tools.UrlUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileService {

@Value("${upload.filePath}")
private String filePath;

public String uploadFile(byte[] file, String finalPath, String finalName){
File targetFile = new File(finalPath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out;
try {
out = new FileOutputStream(finalPath+finalName);

out.write(file);
out.flush();
out.close();

} catch (IOException e) {
e.printStackTrace();
return "uploadimg failure: " + e.getMessage();
}

System.out.println(finalPath + finalName);
return finalPath + finalName;
}

public void uploadFile(InputStream in, String finalPath,
String finalName) throws IOException {

File targetFile = new File(finalPath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//创建一个文件输出流
FileOutputStream out = new FileOutputStream(finalPath + finalName);
//创建一个缓冲区
byte buffer[] = new byte[1024];
//判断输入流中的数据是否已经读完的标识
int len = 0;
//循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
while((len=in.read(buffer))>0){
//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
out.write(buffer, 0, len);
}
in.close();
//关闭输出流
out.close();
}

public String uploadFileByURL(String folder, String urlStr) throws IOException {

SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
String suffix = HttpURLConnection.guessContentTypeFromName(urlStr).split("/")[1];
String fileName = UUID.randomUUID()+"."+suffix;
String relativePath = folder +"/" + sf.format(new Date()) +"/";
String absolutePath=filePath.replace("\\", "/") + relativePath;

File targetFile = new File(absolutePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
URL url = new URL(UrlUtil.toUtf8String(urlStr));

File file = new File(absolutePath+fileName);

// 打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式为"GET"
conn.setRequestMethod("GET");
// 超时响应时间为5秒
conn.setConnectTimeout(5 * 1000);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

// 通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
System.out.println(HttpURLConnection.guessContentTypeFromStream(inStream));
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 创建一个Buffer字符串
byte[] buffer = new byte[1024];
// 每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
// 使用一个输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer)) != -1) {
// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 关闭输入流
inStream.close();
// 创建输出流
FileOutputStream outStream2 = new FileOutputStream(file);
// 写入数据
outStream2.write(outStream.toByteArray());
// 关闭输出流
outStream2.close();

return relativePath+fileName;
}
}

简单的文件上传下载示例,具体代码可以下载github下来看看

效果图

"图片描述"

源码:https://github.com/qq1028951741/springbootdemo or 右上角github进去,springbootdemo项目,如果对您有帮助,麻烦点下star,谢谢


人生两苦:想要却不得,拥有却失去。 –褚禄山
珍惜当下,与君共勉~


本文标题:SpringBoot:文件上传接收&&http图片获取

文章作者:fufua

发布时间:2018年11月29日 - 10:43:13

最后更新:2018年12月03日 - 15:06:12

原始链接:https://qq1028951741.github.io/2018/11/29/SpringBoot:文件上传接收&&http图片获取/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

this is end, thank you for reading