[Program] image upload

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_42322103/article/details/98170833

In a recent project to imitate an enterprise-class learning to do and would like to feel a large and complete project is what it looks like. In the process of learning with pictures uploaded my experience up to record here.

The front section

The front part using element-ui, find the "Upload" super easy assembly :: http://element-ui.cn/#/zh-CN/component/upload
parameters related document describes in great detail can substantially directly used to use it

The following are examples of when to use for reference, because it involves interaction with back-end, rather than pure UI

Core code (html)

	<el-form-item label="品牌图片">
		<el-upload
			class="avatar-uploader"
			action="/upload/native.do"
			:show-file-list="false"
			:on-success="handleAvatarSuccess"
			:before-upload="beforeAvatarUpload">
			<img v-if="imageUrl" :src="imageUrl" class="avatar">
			<i v-else class="el-icon-plus avatar-uploader-icon"></i>
		</el-upload>
	</el-form-item>	

Parameters: imageUrl: ''
style:

	<style>
			.avatar-uploader .el-upload {
				border: 1px dashed #d9d9d9;
				border-radius: 6px;
				cursor: pointer;
				position: relative;
				overflow: hidden;
			}
			.avatar-uploader .el-upload:hover {
				border-color: #409EFF;
			}
			.avatar-uploader-icon {
				font-size: 28px;
				color: #8c939d;
				width: 178px;
				height: 178px;
				line-height: 178px;
				text-align: center;
			}
			.avatar {
				width: 178px;
				height: 178px;
				display: block;
			}
		</style>

The core part (interaction with back-end)

	handleAvatarSuccess(res, file) {
						this.imageUrl = file.response; //返回文件的具体物理地址
				},
				beforeAvatarUpload(file) {
						const isJPG = file.type === 'image/jpeg';
						const isLt2M = file.size / 1024 / 1024 < 2;

						if (!isJPG) {
							this.$message.error('上传头像图片只能是 JPG 格式!');
						}
						if (!isLt2M) {
							this.$message.error('上传头像图片大小不能超过 2MB!');
						}
						return isJPG && isLt2M;
				}
			}

The rear end portion

SpringMVC receiving image upload

SpringMVC uploaded, the file is achieved by MultipartResolver. So, if you want to upload files, as long as the corresponding MultipartResolver in spring-mvc.xml registered.
MultipartResolver implementation class has two:

  1. CommonsMultipartResolver
  2. StandardServletMultipartResolver

The difference between the two:

  1. The first requires the use of Apache's commons-fileupload jar package and other support, but it can be used in older servlet version.
  2. The second jar package does not require third-party support, it uses the built-in servlet upload function, but can only be used in more than Servlet3 version.

Is now more of a way to use.

Related dependence
application-json.xml (fastjson configuration information and the like)

<!-- 多部分文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="104857600" />
		<property name="maxInMemorySize" value="4096" />
		<property name="defaultEncoding" value="UTF-8"></property>
	</bean>

pom.xml

    <!--文件上传-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>

maxUploadSize: upload setting allows maximum file size in bytes is calculated. When set to -1 represents unlimited, the default is -1.

defaultEncoding: indicates the default encoding format to parse request requested, the time is not specified when the default value is used according to ISO-8859-1 Servlet specification. When the request specifies its own encoding format when it will ignore specified here defaultEncoding.

Back-end code

package com.qingcheng.controller.file;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private HttpServletRequest request;  //获取servlet的路径 直接无法获取

    //MultipartFile文件的二进制内容
    @PostMapping("/native")
    public String nativeUpload(@RequestParam("file") MultipartFile file){
        String path = request.getSession().getServletContext().getRealPath("img"); //获取路径下的img目录
        String filePath = path+"/"+file.getOriginalFilename();  //目录加文件名
        File desFile = new File(filePath);
        if(!desFile.getParentFile().exists()){ //上级目录是否存在
            desFile.mkdirs();
        }
        try {
            file.transferTo(desFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "http://localhost:9101/img/"+file.getOriginalFilename();
    }
}

effect:
Here Insert Picture Description
Here Insert Picture Description

recording

Long experience of place here, is that cloud storage solution - Ali cloud OSS

Ali cloud object storage service (Object Storage Service, referred to as OSS) provides network-based data access services. The use of OSS, you can always store and recall all kinds of unstructured data files, including text, images, audio and video, etc., through the network.

Ali cloud OSS data files to objects (object) of storage space spread form (bucket) in the.

The following operations:

  • Create one or more storage space, add one or more files to each storage space.
  • Share and download files by getting the uploaded file address.
  • To set the appropriate access rights or attributes by modifying meta information of a file or storage space.
  • Perform basic and advanced tasks in the OSS Ali cloud management console.
  • Ali cloud use development kit or call RESTfulAPI perform basic and advanced OSS tasks directly in the application

Important, although no student discounts! ! ! But for me this is very user very, very cheap:
https://www.aliyun.com/product/oss?spm=5176.12825654.eofdhaal5.81.247b2c4atp1TcJ

I feel a dollar is enough long, long time
Here Insert Picture Description
backstage was very friendly
Here Insert Picture Description
document is also the OK https://help.aliyun.com/document_detail/31817.html?spm=a2c4g.11174283.2.2.494c7da2dX9ytJ

It provides a very comprehensive program, which is perhaps the giant bar
Here Insert Picture Description
official website provides dependent

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.5.0</version>
</dependency>

There in the document "simple upload" to upload detailed description of the operation area of ​​the copy I have here is to upload a file stream

// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";

// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 上传文件流。
InputStream inputStream = new FileInputStream("<yourlocalFile>");
ossClient.putObject("<yourBucketName>", "<yourObjectName>", inputStream);


// 关闭OSSClient。
ossClient.shutdown();				

endpoint management can be found in the background
Here Insert Picture Description
get accessKeyId and accessKeySecret of:

Because I am a registered not long need to create their own look
Here Insert Picture Description
Here Insert Picture Description
yourBucketName Bucket is just created
yourObjectName is to upload the file name

If the spring and then in conjunction with such a large piece of code may be configured to spring the bean

application-json.xml

	<!--阿里云OSS  -->
	<bean id="ossClient" class="com.aliyun.oss.OSSClient">
		<constructor-arg index="0" value="oss-cn-qingdao.aliyuncs.com"></constructor-arg>
		<constructor-arg index="1" value="AccessKeyID"></constructor-arg>
		<constructor-arg index="2" value="AccessKeySecret"></constructor-arg>
	</bean>

When needed can be used directly like this

   @Autowired
    private OSSClient ossClient;
    @PostMapping("/oss")
    public String ossUpload(@RequestParam("file") MultipartFile file){
        String bucketName = "qingcheng-ecp";
        String fileName = file.getOriginalFilename();
        try {
            ossClient.putObject(bucketName,fileName,file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "https://"+bucketName+".oss-cn-qingdao.aliyuncs.com/"+fileName;
    }

Note that this code is problematic, if the uploaded file the same name, then cause a conflict of
improvement is very simple, you can use the time what I used here UUID

     String fileName = UUID.randomUUID()+file.getOriginalFilename();

Another problem is the classification management, all things are put together, it is more difficult to manage things so you can now Ali cloud OSS management background to create a directory in your own back-end code to add

floder is passed over by the front end of this more flexible Ha

@Autowired
    private OSSClient ossClient;
    @PostMapping("/oss")
    public String ossUpload(@RequestParam("file") MultipartFile file,String folder){
        String bucketName = "qingcheng-ecp";
        String fileName = folder+"/"+UUID.randomUUID()+file.getOriginalFilename();
        try {
            ossClient.putObject(bucketName,fileName,file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "https://"+bucketName+".oss-cn-qingdao.aliyuncs.com/"+fileName;
    }

Here Insert Picture Description
Ali cloud OSS background
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/qq_42322103/article/details/98170833