1.页面效果以及JS
<!-- HTML -->
<div style="margin:30px;"><div class="form-horizontal rowt"><div class="control-label col-lg-1">标书分类</div><div class="col-lg-2"><select required="required" id="category" class="form-control"><option value="" selected>请选择</option></select></div></div><div class="form-horizontal rowt" style="margin-top:20px;"><div class="control-label col-lg-1" >上传文件</div><div class="col-lg-2" style="margin-top: 7px;"></label><input id="uploadfile" type="file" /></div></div><div class="rowt"><div style="margin:20px 126px;"><button id="upload" type="button" class="btn btn-primary" data-toggle="button" aria-pressed="false" autocomplete="off">提交</button><button id="goShareBookPage" type="button" class="btn btn-primary" data-toggle="button" aria-pressed="false" autocomplete="off">返回</button></div></div>
</div>
<!-- JS -->
$("#upload").click(function(){var category = $("#category").val();var file = $("#uploadfile").val();if(category!='' && category!=null){if (file!=null && file!='') {var fileData = new FormData();var file = document.getElementById("uploadfile");var filObj = file.files[0];fileData.append("file",filObj); //上传文件参数fileData.append("category",category); //其他参数$.ajax({xhrFields: {withCredentials: true},url:baseUrl+"/shareBookApi/uploadFile",type:'POST', contentType:false, //避免JQuery对其操作,详解https://blog.csdn.net/toubaokewu/article/details/74910799#commentseditprocessData:false, //告诉jQuery不要去处理发送的数据async:false, //async. 默认是 true,即为异步方式;设置为 false,则所有的请求均为同步请求data:fileData,success:function (data) {if(data!='' && data !=null){alert('上传成功,等待审核!');}else{alert('上传失败!');}},error: function (data) {console.log(data);alert('上传失败!');}});}else{alert('请选择文件!'); }}else{alert('请选择分类!');}});
2.后端代码
阿里云OSS服务类
package cn.stylefeng.guns.modular.system.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;/*** 阿里云OSS服务类*/
@Slf4j
public class AliyunOssUtil {//Endpointpublic static final String Endpoint="***";public final static String accessKeyId = ***;public final static String secretaccesskey = ***;public final static String BUCKET_NAME=***/*** 删除一个Bucket和其中的Objects** @param //client* @param //bucketName* @throws OSSException* @throws ClientException*/public static void deleteBucket(OSSClient client)throws OSSException, ClientException {ObjectListing ObjectListing = client.listObjects(BUCKET_NAME);List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();for (int i = 0; i < listDeletes.size(); i++) {String objectName = listDeletes.get(i).getKey();// 如果不为空,先删除bucket下的文件client.deleteObject(BUCKET_NAME, objectName);}client.deleteBucket(BUCKET_NAME);}/*** 把Bucket设置为所有人可读** @param //client* @param //bucketName* @throws OSSException* @throws ClientException*/public static void setBucketPublicReadable(OSSClient client)throws OSSException, ClientException {//创建bucketclient.createBucket(BUCKET_NAME);//设置bucket的访问权限,public-read-write权限client.setBucketAcl(BUCKET_NAME, CannedAccessControlList.PublicRead);}/*** 上传文件** @param //client* @param filename* @throws OSSException* @throws ClientException* @throws FileNotFoundException*/public static String uploadFile(String filename) {try {OSSClient client = getOssClient();log.info("filename:"+filename);File file = new File(filename);ObjectMetadata objectMeta = new ObjectMetadata();objectMeta.setContentLength(file.length());String type=getContentType(filename);objectMeta.setContentType(type==null?"image/gif":type);InputStream input = new FileInputStream(file);String key=type+"/"+IDUtils.genImageName();PutObjectResult result = client.putObject(BUCKET_NAME, key, input, objectMeta);if(result!=null){return getUrl(client,key);}}catch (Exception e){e.printStackTrace();log.error(e.getMessage());}return null;}/*** 下载文件** @param //client* @param //bucketName* @param key* @param filename 新文件名* @throws OSSException* @throws ClientException*/public static InputStream downloadFile(OSSClient client, String key, String filename)throws OSSException, ClientException {
// Object obj = client.getObject(new GetObjectRequest(BUCKET_NAME, key),
// new File(filename));OSSObject ossObject = client.getObject(BUCKET_NAME, key);return ossObject.getObjectContent();}/*** 创建一个文件夹** @param //client* @param //bucketName* @param folderPah 文件夹名*/public static void createFolder(String folderPah) {OSSClient client = getOssClient();ObjectMetadata objectMeta = new ObjectMetadata();byte[] buffer = new byte[0];ByteArrayInputStream in = new ByteArrayInputStream(buffer);objectMeta.setContentLength(0);try {client.putObject(BUCKET_NAME, folderPah, in, objectMeta);} catch (Exception e) {e.printStackTrace();} finally {try {in.close();} catch (IOException e) {e.printStackTrace();}}}/*** 获得url链接** @param key* @return*/public static String getUrl(OSSClient ossClient,String key) {// 设置URL过期时间为10年 3600l* 1000*24*365*10Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);// 生成URLURL url = ossClient.generatePresignedUrl(BUCKET_NAME, key, expiration);if (url != null) {return url.toString();}return null;}/*** 获取文件类型* @param fileName* @return*/public static String getContentType(String fileName) {String fileExtension = fileName.substring(fileName.lastIndexOf("."));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(".json".equalsIgnoreCase(fileExtension)){return "json";}if(".mp3".equalsIgnoreCase(fileExtension)){return "mp3";}if(".txt".equalsIgnoreCase(fileExtension)){return "txt";}if(".doc".equalsIgnoreCase(fileExtension)){return "doc";}if(".docx".equalsIgnoreCase(fileExtension)){return "docx";}return null;}/*** * 上传图片至OSS* * @param file* * @return* */public static String uploadFile(MultipartFile file) {log.info("oos上传");String resultStr = null;try {OSSClient client = getOssClient();String fileName = file.getOriginalFilename();Long fileSize = file.getSize();ObjectMetadata metadata = new ObjectMetadata();metadata.setContentLength(fileSize);metadata.setCacheControl("no-cache");metadata.setHeader("Pragma", "no-cache");metadata.setContentEncoding("utf-8");String type=getContentType(fileName);metadata.setContentType(getContentType(fileName));metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");//上传文件String key=type+"/"+IDUtils.genImageName();PutObjectResult result = client.putObject(BUCKET_NAME, key, file.getInputStream(), metadata);if(result!=null){resultStr= getUrl(client,key);}} catch (IOException e) {e.printStackTrace();}log.info("resultStr"+resultStr);return resultStr;}/*** 上传到OSS服务器 如果同名文件会覆盖服务器上的** @param instream 文件流* @param fileName 文件名称 包括后缀名* @return 出错返回"" ,唯一MD5数字签名*/public static String uploadFile2OSS(InputStream instream, String fileName) {String ret = "";try {//创建上传Object的MetadataOSSClient client = getOssClient();ObjectMetadata objectMetadata = new ObjectMetadata();objectMetadata.setContentLength(instream.available());objectMetadata.setCacheControl("no-cache");objectMetadata.setHeader("Pragma", "no-cache");objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));objectMetadata.setContentDisposition("inline;filename=" + fileName);//上传文件String name=System.currentTimeMillis()+"";PutObjectResult putResult = client.putObject(BUCKET_NAME, name, instream, objectMetadata);ret = putResult.getETag();return getUrl(client,name);} catch (IOException e) {log.error(e.getMessage(), e);} finally {try {if (instream != null) {instream.close();}} catch (IOException e) {e.printStackTrace();}}return null;}/*** 流式上传文件-上传文件流* InputStream inputStream = new FileInputStream("localFile");*/public static String upFObject(MultipartFile inputStream){try {OSSClient client = getOssClient();if(!client.doesBucketExist(BUCKET_NAME)){client.createBucket(BUCKET_NAME);}String filename = inputStream.getOriginalFilename(); //文件名带后缀.txtString prefix = filename.substring(filename.lastIndexOf(".") + 1);System.out.println(prefix);ObjectMetadata metadata = new ObjectMetadata();metadata.setContentLength(inputStream.getSize());metadata.addUserMetadata("filename", "123");String reName = IDUtils.genImageName()+"."+prefix;//浏览器下载metadata.setContentDisposition("attachment;filename="+reName);String key="json"+"/"+reName;client.putObject(BUCKET_NAME, key, new ByteArrayInputStream(inputStream.getBytes()), metadata);//获取该文件在阿里云的路径client.shutdown();return getUrl(client,key);}catch (Exception e){e.printStackTrace();}return null;}/*** 删除一个OSS文件对象** @param //client* @param //bucketName* @param key*/public static void deleteObject( String key) {OSSClient client = getOssClient();client.deleteObject(BUCKET_NAME, key);}public static OSSClient getOssClient() {return new OSSClient(Endpoint, accessKeyId, secretaccesskey);}public static void main(String[] args) {OSSClient client = getOssClient();String String=uploadFile("C:\\Users\\jiuying\\Desktop\\新建文本文档.txt");System.out.println(String);}
}
上传图片控制层
/*** @author * @date Learning never ends*/
@Controller
@Slf4j
public class ShareBookApiController {/*** 上传文件并添加标书*/@RequestMapping(value = "/uploadFile")@ResponseBodypublic Object getuploadFile(MultipartFile file,String category, HttpServletRequest request) {System.out.println(file.getOriginalFilename() + "getOriginalFilename");System.out.println(file.getContentType() + "getContentType");System.out.println(file.getSize() + "getSize");String fileUrl = AliyunOssUtil.upFObject(file);return "success";}}