上传文件,以及通过 Feign 调用上传文件接口

上传文件,以及通过 Feign 调用上传文件接口,第1张

(1)工具类

(2)定义接口

(3)调用 http://localhost:8080/image/upload 进行测试。

在目标文件夹中会出现上传的文件。

(1)定义一个 FeignClient 。

(2)调用上面定义的 FeignClient 接口。

(3)调用 http://localhost:8080/test 接口,控制台输出如下:

说明一切正常。

以下代码使用分片上传的方式,可有效解决,OSS文件上传缓慢问题,但如果服务器的宽带过低还是会影响上传速度,可将服务器宽带提高,以提升速度

1.引入POM

<!--阿里云OSS-->

<dependency>

<groupId>com.aliyun.oss</groupId>

<artifactId>aliyun-sdk-oss</artifactId>

<version>3.9.1</version>

</dependency>

1

2

3

4

5

6

7

1

2

3

4

5

6

7

2.编写文件上传工具类

import com.alibaba.fastjson.JSONObject

import com.aliyun.oss.ClientBuilderConfiguration

import com.aliyun.oss.OSS

import com.aliyun.oss.OSSClientBuilder

import com.aliyun.oss.model.*

import org.springframework.web.multipart.MultipartFile

import java.io.*

import java.net.URL

import java.text.SimpleDateFormat

import java.util.*

import java.util.concurrent.ExecutorService

import java.util.concurrent.Executors

import java.util.concurrent.TimeUnit

/**

* 文件上传工具类

*/

public class FilesUploadUtil {

/**

* 获取上传结果

* @param newFile 上传文件

* @param folder 父级文件夹名称

* @return 文件访问路径

*/

public static JSONObject obtainTheFileUploadResult(MultipartFile newFile, String folder){

JSONObject result=new JSONObject()

JSONObject data=new JSONObject()

long startTime = System.currentTimeMillis()

try {

// MultipartFile 转 File

File file=multipartFileToFile(newFile)

//上传文件

String[] resultArr = uploadObject2OSS(file, folder)

if (resultArr != null) {

String path = resultArr[1]

//绝对路径,拼接CND加速域名,或自己的域名

data.put("src", "自己的公网IP".concat("/").concat(path))

//相对路径

data.put("relativePath", path)

result.put("msg", 1)

result.put("errorMessage", null)

}

// 删除本地临时文件

deleteTempFile(file)

} catch (RuntimeException e) {

e.printStackTrace()

result.put("msg", 0)

result.put("errorMessage", "文件大小不能超过9.7G")

data.put("src", null)

data.put("relativePath", null)

}catch (Exception e) {

result.put("msg", 0)

result.put("errorMessage", "上传错误:"+e.getMessage())

data.put("src", null)

data.put("relativePath", null)

}

result.put("data",data)

long endTime = System.currentTimeMillis()

System.out.println("------文件上传成功,耗时" + ((endTime - startTime) / 1000) + "s------")

return result

}

/**

* 上传图片至OSS 文件流

*

* @param file 上传文件(文件全路径如:D:\\image\\cake.jpg)

* @param folder 阿里云API的文件夹名称(父文件夹)

* @return String 返回的唯一MD5数字签名

*/

public static String[] uploadObject2OSS(File file,String folder) throws Exception{

//获取OSS客户端对象

OSS ossClient=getOSSClient()

//OOS 桶名称 bucketName

String bucketName="自己阿里云的bucketName"

// 阿里OSS

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd")

Date date = new Date()

// 阿里云API的文件夹名称(子文件夹)

String format = dateFormat.format(date) + "/"

// 文件名

String formats =String.valueOf(UUID.randomUUID())

// 创建一个可重用固定线程数的线程池

ExecutorService executorService = Executors.newFixedThreadPool(5)

String[] resultArr = new String[2]

try {

// 分片上传

folder =folder +"/"+ format

// 文件名

String fileName = file.getName()

// 文件扩展名

String fileExtension = fileName.substring(fileName.lastIndexOf("."))

// 最终文件名:UUID + 文件扩展名

fileName = formats + fileExtension

// 上传路径 如:appversion/20200723/a3662009-897c-43ea-a6d8-466ab8310c6b.apk

// objectName表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg

String objectName = folder + fileName

System.out.println("文件路径--》》"+objectName)

// 文件大小

long fileSize = file.length()

// 创建上传Object的Metadata

ObjectMetadata metadata = new ObjectMetadata()

// 指定该Object被下载时的网页的缓存行为

metadata.setCacheControl("no-cache")

// 指定该Object下设置Header

metadata.setHeader("Pragma", "no-cache")

// 指定该Object被下载时的内容编码格式

metadata.setContentEncoding("utf-8")

// 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,

// 如果没有扩展名则填默认值application/octet-stream

metadata.setContentType(getContentType(fileExtension))

// 指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)

metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.")

// 创建InitiateMultipartUploadRequest对象

InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName, metadata)

// 初始化分片

InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request)

// 返回uploadId,它是分片上传事件的唯一标识,您可以根据这个uploadId发起相关的 *** 作,如取消分片上传、查询分片上传等

String uploadId = upresult.getUploadId()

// partETags是PartETag的集合。PartETag由分片的ETag和分片号组成

List<PartETag>partETags = Collections.synchronizedList(new ArrayList<>())

// 计算文件有多少个分片

final long partSize = 1 * 1024 * 1024L// 1MB

long fileLength = file.length()

int partCount = (int) (fileLength / partSize)

if (fileLength % partSize != 0) {

partCount++

}

if (partCount >10000) {

throw new RuntimeException("文件过大")

}

// 遍历分片上传

for (int i = 0i <partCounti++) {

long startPos = i * partSize

long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize

int partNumber = i + 1

// 实现并启动线程

executorService.execute(new Runnable() {

@Override

public void run() {

InputStream inputStream = null

try {

inputStream = new FileInputStream(file)

// 跳过已经上传的分片

inputStream.skip(startPos)

UploadPartRequest uploadPartRequest = new UploadPartRequest()

uploadPartRequest.setBucketName(bucketName)

uploadPartRequest.setKey(objectName)

uploadPartRequest.setUploadId(uploadId)

uploadPartRequest.setInputStream(inputStream)

// 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100 KB。

uploadPartRequest.setPartSize(curPartSize)

// 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出这个范围,OSS将返回InvalidArgument的错误码。

uploadPartRequest.setPartNumber(partNumber)

// 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。

UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest)

//每次上传分片之后,OSS的返回结果会包含一个PartETag。PartETag将被保存到PartETags中。

synchronized (partETags) {

partETags.add(uploadPartResult.getPartETag())

}

} catch (IOException e) {

e.printStackTrace()

} finally {

if (inputStream != null) {

try {

inputStream.close()

} catch (IOException e) {

e.printStackTrace()

}

}

}

}

})

}

// 等待所有的分片完成

// shutdown方法:通知各个任务(Runnable)的运行结束

executorService.shutdown()

while (!executorService.isTerminated()) {

try {

// 指定的时间内所有的任务都结束的时候,返回true,反之返回false,返回false还有执行完的任务

executorService.awaitTermination(5, TimeUnit.SECONDS)

} catch (InterruptedException e) {

System.out.println(e.getMessage())

}

}

// 立即关闭所有执行中的线程

// executorService.shutdownNow()

// 验证是否所有的分片都完成

if (partETags.size() != partCount) {

throw new IllegalStateException("文件的某些部分上传失败!")

}

// 完成分片上传 进行排序。partETags必须按分片号升序排列

Collections.sort(partETags, new Comparator<PartETag>() {

@Override

public int compare(PartETag o1, PartETag o2) {

return o1.getPartNumber() - o2.getPartNumber()

}

})

// 创建CompleteMultipartUploadRequest对象

// 在执行完成分片上传 *** 作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件

CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags)

// 设置文件访问权限

// completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.PublicRead)

// 完成上传

CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest)

if (completeMultipartUploadResult != null) {

// 解析结果

resultArr[0] = completeMultipartUploadResult.getETag()

resultArr[1] = objectName

return resultArr

}

} catch (Exception e) {

e.printStackTrace()

System.out.println("上传阿里云OSS服务器异常." + e.getMessage())

} finally {

// 关闭OSSClient

ossClient.shutdown()

}

return null

}

/**

* MultipartFile 转 File

*

* @param file

* @throws Exception

*/

public static File multipartFileToFile(MultipartFile file) {

try {

File toFile

if (file != null &&file.getSize() >0) {

InputStream ins = null

ins = file.getInputStream()

toFile = new File(file.getOriginalFilename())

inputStreamToFile(ins, toFile)

ins.close()

return toFile

}

return null

} catch (IOException e) {

e.printStackTrace()

return null

}

}

/**

* 获取流文件

*

* @param ins

* @param file

*/

public static void inputStreamToFile(InputStream ins, File file) {

try {

OutputStream os = new FileOutputStream(file)

int bytesRead

byte[] buffer = new byte[8192]

while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {

os.write(buffer, 0, bytesRead)

}

os.close()

ins.close()

} catch (Exception e) {

e.printStackTrace()

}

}

/**

* 获取阿里云OSS客户端对象

*

* @return ossClient

*/

public static OSS getOSSClient() {

ClientBuilderConfiguration conf = new ClientBuilderConfiguration()

// 连接空闲超时时间,超时则关闭

conf.setIdleConnectionTime(1000)

return new OSSClientBuilder().build("自己阿里云的endpoint", "自己阿里云的access_key_id", "自己阿里云的access_key_secret", conf)

}

/**

* 获得url链接

*

* @param bucketName 桶名称

* @param keyBucket下的文件的路径名+文件名 如:"appversion/20200723/a3662009-897c-43ea-a6d8-466ab8310c6b.apk"

* @return 图片链接:http://xxxxx.oss-cn-beijing.aliyuncs.com/test/headImage/1546404670068899.jpg?Expires=1861774699&OSSAccessKeyId=****=p%2BuzEEp%2F3JzcHzm%2FtAYA9U5JM4I%3D

* (Expires=1861774699&OSSAccessKeyId=LTAISWCu15mkrjRw&Signature=p%2BuzEEp%2F3JzcHzm%2FtAYA9U5JM4I%3D 分别为:有前期、keyID、签名)

*/

public static String getUrl(String bucketName, String key) {

// 设置URL过期时间为10年 3600L*1000*24*365*10

Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10)

OSS ossClient = getOSSClient()

// 生成URL

URL url = ossClient.generatePresignedUrl(bucketName, key, expiration)

return url.toString().substring(0, url.toString().lastIndexOf("?"))

}

/**

* 删除本地临时文件

*

* @param file

*/

public static void deleteTempFile(File file) {

if (file != null) {

File del = new File(file.toURI())

del.delete()

}

}

/**

* 通过文件名判断并获取OSS服务文件上传时文件的contentType

*

* @param fileExtension 文件名扩展名

* @return 文件的contentType

*/

public static String getContentType(String fileExtension) {

// 文件的后缀名

if (".bmp".equalsIgnoreCase(fileExtension)) {

return "image/bmp"

}

if (".gif".equalsIgnoreCase(fileExtension)) {

return "image/gif"

}

if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)

|| ".png".equalsIgnoreCase(fileExtension)) {

return "image/jpeg"

}

if (".html".equalsIgnoreCase(fileExtension)) {

return "text/html"

}

if (".txt".equalsIgnoreCase(fileExtension)) {

return "text/plain"

}

if (".vsd".equalsIgnoreCase(fileExtension)) {

return "application/vnd.visio"

}

if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {

return "application/vnd.ms-powerpoint"

}

if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {

return "application/msword"

}

if (".xml".equalsIgnoreCase(fileExtension)) {

return "text/xml"

}

if (".mp4".equalsIgnoreCase(fileExtension)) {

return "video/mp4"

}

// android

if (".apk".equalsIgnoreCase(fileExtension)) {

return "application/vnd.android.package-archive"

}

// ios

if (".ipa".equals(fileExtension)) {

return "application/vnd.iphone"

}

// 默认返回类型

return "application/octet-stream"

}

}

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

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

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

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

3.controller编写

/**

* 上传文件

*

* @param file 文件

* @return

* @throws IOException

*/

@ResponseBody

@RequestMapping(value = "/urevf", method = RequestMethod.POST, produces = "application/jsoncharset=UTF-8")

public JSONObject uploadRealEstateVideoFiles(@RequestParam(value = "file") MultipartFile file) throws IOException {

//此处的video_file为阿里云OSS上最外层文件夹,自己新建即可

return FilesUploadUtil.obtainTheFileUploadResult(file, "video_file")

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

1

2

3

4

5

6

7

8

9

10

11

12

13

14

实际工作中我们都会使用第三方工具类:commons-fileupload.

通过文件传输的表单提交方式提交之后,在servlet中用request.getparameter(“xx”)获取不到数据.


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/6041052.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-12
下一篇 2023-03-12

发表评论

登录后才能评论

评论列表(0条)

保存