directory

1. Ajax technology

2. The HTML content

3. The Java code

4. Java tools

5. Pom.xml introduces dependencies


 

1. Ajax technology

Function clickUPFile(){var formData =new formData (); formdata.append('enctype', 'multipart/form-data'); formdata.append('name', 'file'); formdata.append('file',$('#file').get(0).files[0]); // formdata.append('recid',str); $.ajax({ url:porject.host+'/2/serviceUploadas', type:'post', contentType:false, data:formdata, processData:false, success:function(info){ console.log(info) // $('.backimg').attr('src',JSON.parse(info).msg); }, error:function(err){ console.log(err) } }); }Copy the code

 

2. The HTML content

 <input type="file" name="file"  id="file"/>
 <input type="submit" value="Upload file" onclick="clickUPFile();" />
Copy the code

 

3. The Java code

/** * File upload method **@param file
	 * @param session
	 * @return* /
	@RequestMapping("/2/serviceUploadas")
	@ResponseBody
	public String serviceUploadas(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
 
		// The file is judged to be empty
		if (file.isEmpty())
			return "Upload failed, please select file";

		// Get the original file name
		String fileOriginalName = file.getOriginalFilename();

		// Verify file name security
		if (fileOriginalName.indexOf(".") != -1) {// The judge contains the file with the ending character
			// Only JPG files can be uploaded
			if (fileOriginalName.split("\ \.") [1].equals("jpg")) {
				String fliePrefix = UUID.randomUUID().toString().replace("-"."");
				String key = new StringBuffer("/superf/u_").append(fliePrefix).append(".")
						.append(fileOriginalName.split("\ \.") [1]).toString();

				File excelFile = null;
				try {
					excelFile = File.createTempFile(key, ".jpg");
					file.transferTo(excelFile);

					// Execute the upload method
					if(fu.upLoadFileTX(key, excelFile) ! =null)
						return ServerUrlImg + key;

				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if(excelFile.exists()) { excelFile.delete(); }}}}return "error";
	}
Copy the code

 

4. Java tools

package com.supermap.file;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import ch.qos.logback.classic.Logger;

/** * File server public class **@author yushen
 *
 */
@Component
public class FileUitl {

	@Value("${fileuitl.akid}")
	private String AKID;

	@Value("${fileuitl.akd}")
	private String AKD;

	@Value("${fileuitl.region}")
	private String Region;

	@Value("${fileuitl.bucketname}")
	private String bucketname;

	private COSClient cosClient;

	private COSClient getClient(a) {
		COSCredentials cred = new BasicCOSCredentials(AKID, AKD);
		ClientConfig clientConfig = new ClientConfig(new Region(Region));
		cosClient = new COSClient(cred, clientConfig);
		return cosClient;
	}

	public String upLoadFileTX(String key, File file) {
		if (cosClient == null) {
			cosClient = getClient();
		}
		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketname, key, file);
		PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
		return putObjectResult.getETag();
	}

	public void delFileTX(String key) {
		if (cosClient == null) { cosClient = getClient(); } cosClient.deleteObject(bucketname, key); }}Copy the code

 

5. Pom.xml introduces dependencies

 
		<dependency>
          <groupId>com.qcloud</groupId>
          <artifactId>cos_api</artifactId>
          <version>5.4.10</version>
		</dependency>
Copy the code