1. 程式人生 > >圖片批量上傳到阿里雲伺服器

圖片批量上傳到阿里雲伺服器

上傳圖片頁面

<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>上傳圖片</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
  </head>
  
  <body>
    <form action="publishInfo" method="post" enctype="multipart/form-data">
   <input type="file" name="file"/>
   <input type="file" name="file"/><br/>
   分類id:<input type="text" name="classifyId" /><br/>
   商圈Id:<input type="text" name="zoneId" /><br/>
   使用者id:<input type="text" name="userId" /><br/>
  內容:<input type="text" name="content" /><br/>
   釋出地點:<input type="text" name="releasePlace" /><br/>
  登入token: <input type="text" name="token" /><br/>
  <input type="submit" value="提交"/>
  </form>
  </body> 
</html>

Controller層

@ApiOperation(value = "修改釋出訊息介面", httpMethod = "PUT", notes = "updateInformation")
@RequestMapping("/updateInformation")
@TokenValidate(tokenValidate = true,jurisdiction=1)
@ResponseBody
@SameUrlData
public BaseModel updateInformation(@Validated  Information info,
BindingResult result,
@RequestParam(value = "token") String loginToken,
@RequestParam("file") MultipartFile files[],
HttpServletRequest request) throws Exception {
BaseModel baseModel = new BaseModel();
User user = UserLoginMap.getUserLoginMap().getUser(loginToken);
Map<String, Object> mapResults = new HashMap<String, Object>(16);
if (user != null) {
try {
if (result.hasErrors()) {
List<ObjectError> allError = result.getAllErrors();
for (ObjectError objectError : allError) {
System.out.println(objectError.getDefaultMessage());
}
mapResults.put("allErrors", allError);
baseModel.setMapResults(mapResults);
return baseModel;
}
List<String> list = new ArrayList<String>();
// 獲得專案的路徑
System.out.println("file3  "+files);
ServletContext sc = request.getSession().getServletContext();
// 上傳位置
String path = sc.getRealPath("/upload") + "/"; // 設定檔案儲存的目�?
File f = new File(path);
if (!f.exists())
f.mkdirs();
for (int i = 0; i < files.length; i++) {
// 獲得原始檔名
String fileName = files[i].getOriginalFilename();
System.out.println("原始檔案:" + fileName);
// 新檔名
if (!files[i].isEmpty()) {
String newFileName = UUID.randomUUID() + fileName;
FileOutputStream fos = new FileOutputStream(path
+ newFileName);
InputStream in = files[i].getInputStream();
int b = 0;
while ((b = in.read()) != -1) {
fos.write(b);
}
fos.close();
in.close();
File file = new File(path + newFileName);
Image image = ImageIO.read(file);
if (image == null) {
// 判斷檔案是否存在
if (file.exists()) {
// 檔案刪除
file.delete();
}
}
ImgCompress.ImgCompressDo(path+newFileName);
WaterMarkUtils.addWaterMark(path+newFileName);
System.out.println("上傳圖片:" + path + newFileName);
list.add(newFileName);
}
}
mapResults.put("updateInformation",
informationService.updateInformation(info, list));
mapResults.put("fileList", path+list);
baseModel.setMapResults(mapResults);
} catch (Exception e) {
e.printStackTrace();
}
} else {
baseModel.setStatus(StatusEnum.UNLOGIN.getStatusCode());
baseModel.setErrorMessage("您未登入!");
}
return baseModel;
}

Mapper層

/**
* 訊息釋出
*/
@Override
public BaseModel insert(Information info, boolean share, List<String> list)
throws Exception {
BaseModel baseModel = new BaseModel();
selectShield();
String img="";
int result = 0;
int variableValue = 0;// 定義全域性引數表的值
System.out.println("待檢測語句字數:" + info.getContent().length());
System.out.println(SensitiveWord.getSensitiveWord(info.getContent(), 1));
// 查詢使用者釋出訊息條數
InformationExample infoExample = new InformationExample();
InformationExample.Criteria infocriteria = infoExample.createCriteria(); // 構�?自定義查詢條�?
infocriteria.andUserIdEqualTo(info.getUserId());
int infoCount = informationMapper.countByExample(infoExample);
// 查詢全域性引數,指定釋出條數後分享
Variable variable = variableMapper
.findVariableByParam("releaseTheNumber");
variableValue = Integer.valueOf(variable.getValue()).intValue();
Date currentTime = new Date();
info.setReleaseTime(currentTime);
int i = 1;
byte state = (byte) i;
info.setState(state);
// 判斷包不包含遮蔽詞
if (SensitiveWord.getSensitiveWord(info.getContent(), 1).isEmpty()) {
// 判斷使用者釋出條數是否應該分享後才能釋出
if (infoCount % variableValue == 0 && share == false) {
baseModel.setStatus(StatusEnum.EXCEPTION.getStatusCode());
baseModel.setErrorMessage("分享後就可以釋出訊息咯");
} else {
System.out.println(list);
if(!list.isEmpty()){
for (String newFileName : list) {
File file=new File(newFileName);
Upload.upload(newFileName);
img=img+","+OssEnum.CNAME.getOssEnum()+file.getName();
}
String imgs = img.substring(1, img.length());
info.setImg(imgs);
}
info.setVersion(UUID.randomUUID().toString());
result = informationMapper.insert(info);
baseModel.setStatus(StatusEnum.SUCCESS.getStatusCode());
}
// 未完成儲存
if (result != 1) {
baseModel.setStatus(StatusEnum.EXCEPTION.getStatusCode());
baseModel.setErrorMessage("操作未完成");
}
} else {
baseModel.setStatus(StatusEnum.OPERATION_FAIL.getStatusCode());
baseModel.setErrorMessage("內容含有敏感詞彙,請稽核內容後再提交");
}
return baseModel;
}

工具類Upload

public class Upload {


    private static String endpoint = OssEnum.ENDPOINT.getOssEnum();
    private static String accessKeyId = OssEnum.ACCESSKEYID.getOssEnum();
    private static String accessKeySecret = OssEnum.ACCESSKESECRET.getOssEnum();
    private static String bucketName = OssEnum.BUCKETNAME.getOssEnum();
    
    public static void upload(String fileKey) throws Exception {
//    String url = "D:\\apache-tomcat-8.0.47\\webapps\\Group2\\upload\\";
//    System.out.println(fileKey.substring(0,fileKey.lastIndexOf("")));
    File file = new File(fileKey);
OSSClient ossClient = new OSSClient(endpoint, accessKeyId,
accessKeySecret);
try {
// 上傳檔案
ossClient.putObject(bucketName, "bobaoge/"+file.getName(), new File(
fileKey));
System.out.println("Object:" + fileKey + "存入OSS成功。");
// 檔案路徑
        // 根據路徑獲取檔案物件
        // 判斷檔案是否存在
        if (file.exists()) {
            // 檔案刪除
            file.delete();
        }
// 檢視Bucket中的Object。詳細請參看“SDK手冊 > Java-SDK > 管理檔案”。
// 連結地址是:https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_object.html?spm=5176.docoss/sdk/java-sdk/manage_bucket
//ObjectListing objectListing = ossClient.listObjects(bucketName);
//List<OSSObjectSummary> objectSummary = objectListing
//.getObjectSummaries();
//System.out.println("您有以下Object:");
//for (OSSObjectSummary object : objectSummary) {
//System.out.println("\t" + object.getKey());
//}
} catch (OSSException oe) {
oe.printStackTrace();
} catch (ClientException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
ossClient.shutdown();
}
    }
}
public enum OssEnum {
     //阿里雲賬號
ENDPOINT("http://oss-cn-beijing.aliyuncs.com"),
     ACCESSKEYID(""),
     ACCESSKESECRET("ii8H3mx5DBmTVrj1n0zb2s7fX0VxH4"),
     CNAME("http://2050fhk.oss-cn-beijing.aliyuncs.com/"),
     BUCKETNAME("");
 
private final String OssEnum;
 
private OssEnum(String ossEnum) {
this.OssEnum = ossEnum;
}


public String getOssEnum() {
return OssEnum;
}
 
}

SpringMvc配置檔案

<!-- 定義檔案直譯器 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
        <!-- 設定預設編碼 -->  
        <property name="defaultEncoding" value="utf-8"></property>  
       <!--上傳圖片最大大小5M   
        <property name="maxUploadSize" value="5242440"></property> -->
        <!-- 上傳臨時目錄 -->    
        <property name="uploadTempDir" value="upload"></property>
    </bean> 

pom配置檔案

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