图片批量上传到阿里云服务器

上传图片页面

<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>


猜你喜欢

转载自blog.csdn.net/qq_36826248/article/details/78837980