上传文件这个功能用的比较多,不难,但是每次写都很别扭。记录在此,以备以后copy用。

package com.**.**.**.web.api;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL; /**
* @Author: zyydd
* @Date: 2019/10/12 14:18
*/
@RestController
@RequestMapping(value = "/api/v1", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class UploadController { private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
/**
* 桶名,取配置
*/
@Value("${jss.bucket}")
private String bucket; private static String key = "file";
private static String springProperties = "application.properties"; @ResponseBody
@RequestMapping(value = "/upload/{fileType}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ApiOperation(value = "文件上传", notes = "文件上传,form-data,key=file;fileType:pic、file", response = String.class, tags = {"UploadController",})
public String uploadFile(HttpServletRequest request, @PathVariable(value = "fileType") String fileType) {
String result = "";
String fileAbsolutePath = "";
try {
logger.info("uploadFile begin! fileType={}", fileType);
//写本地文档
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartHttpServletRequest.getFile(key);
String fileName = multipartFile.getOriginalFilename();
//文件名称加随机数处理,避免重名
fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_" + System.currentTimeMillis() % 1000 + fileName.substring(fileName.lastIndexOf("."));
fileAbsolutePath = getUploadPath() + fileName;
writeFile(fileAbsolutePath, multipartFile.getBytes());
//上传各种云的utils,返回一个上传后可供下载的url,注解掉,按需处理。传入本地文件的绝对路径以及云上桶名
String url = AmazonS3Utils.uploadFileToS3(fileAbsolutePath, bucket);
if (StringUtils.isNotBlank(url)) {
//持久化file数据到数据库,返回数据ID,前台页面根据ID进行挂载,按需处理
Long fileId = fileService.insertFile(url, fileType);
result = fileId + "";
} else {
logger.error("上传云失败,文件本地路径={}", fileAbsolutePath);
result = "上传云失败";
}
} catch (Exception e) {
result = "上传异常";
logger.error("uploadFile exception!", e);
} finally {
//上传完成之后,确保删除本地文件
try {
if (StringUtils.isNotBlank(fileAbsolutePath)) {
File f = new File(fileAbsolutePath);
if (f.exists()) {
f.delete();
}
}
} catch (Exception e) {
logger.error("delete file exception", e);
result = "删除本地文件异常";
}
logger.info("uploadFile end! result={}", result);
return result;
}
} //通过spring的配置文件,来获取war包的绝对路径,并将文件上传到预先准备的文件夹下
private String getUploadPath() {
URL url = this.getClass().getClassLoader().getResource(springProperties);
String uploadPath = url.getPath().replace(springProperties, "upload/");
return uploadPath;
} public static void writeFile(String fileAbsolutePath, byte[] content) throws IOException {
FileOutputStream fos = new FileOutputStream(fileAbsolutePath);
fos.write(content);
fos.close();
} }

相应的,postMan中,调用的示例截图如下

SpringMvc通过controller上传文件代码示例的更多相关文章

  1. springMVC+jsp+ajax上传文件

    工作中遇到的小问题,做个笔记 实现springMVC + jsp + ajax 上传文件 HTML <body> <form id="myform" method ...

  2. springMvc 使用ajax上传文件,返回获取的文件数据 附Struts2文件上传

    总结一下 springMvc使用ajax文件上传 首先说明一下,以下代码所解决的问题 :前端通过input file 标签获取文件,通过ajax与后端交互,后端获取文件,读取excel文件内容,返回e ...

  3. ajaxFileUpload上传文件简单示例

    写在前面: 上传文件的方式有很多,最近在做项目的时候,一开始也试用了利用jquery的插件ajaxFileUpload来上传大文件,下面,用一个上传文件的简单例子,记录下,学习的过程~~~ 还是老样子 ...

  4. SpringMVC+jquery.uploadify 上传文件

    前言 以前用Asp.net MVC+uploadify上传文件,最近学习SpringMVC,所以就用SpringMVC+uploadify做个上传文件的demo. 刚开始用form表单的方式提交,在C ...

  5. iOS上传文件代码,自定义组装body

    以下代码为上传文件所用代码,简单方便,搞了好久,终于知道这么简单的方式来上传. 其它类库也就是把这几句代码封装的乱七八糟得,让你老久搞不懂原理.不就是在body上面加点字符串,body下面加点字符串, ...

  6. ExtJS + fileuploadfield上传文件代码

    后台服务端接收文件的代码: /** * 后台上传文件处理Action */ @RequestMapping(value = "/uploadFile", method=Reques ...

  7. php 上传文件代码

    通过 PHP,能够把文件上传到server.里面加入一些图片的推断,假设不加推断文件的类型就能够上传随意格式的文件. 为了站点的安全,肯定不让上传php文件,假设有人进入你的后台,上传了一个php文件 ...

  8. SpringMVC使用FileUpload上传文件

    进口FileUpload和common-io的Jar包 注意:1.Struts2其它方法需要使用的:struts2过滤,将改变reqeust类型,由HttpServletRequest成为MultiP ...

  9. springMVC结合AjaxForm上传文件

    最近在项目中需要上传文件文件,之前一直都是form提交的,尝试了一下AjaxForm,感觉还比较好用,写篇随笔mark下,供以后使用. 准备工作: 下载jquery-form.js 相关jar: co ...

随机推荐

  1. AEC_js的加解密

    后台传出来,前端就需要转出,前台传入,后台也需要转出 这是前端加解密 /* CryptoJS v3.1.2 */ var CryptoJS = CryptoJS || function(u, p) { ...

  2. .net core+topshelf+quartz创建windows定时任务服务

    .net core+topshelf+quartz创建windows定时任务服务 准备工作 创建.net core 控制台应用程序,这里不做过多介绍 添加TopShelf包:TopShelf: 添加Q ...

  3. C# 文件操作总结

    一.需求分析 1.将信息记录到本地记事本中. 2.将记录的信息读取出来. 3.计算出某个文件夹下所有后缀名为txt的数量和dll的数量. 4.从网络上下载文件. 二.二话不说上代码 using Sys ...

  4. Python关于多继承

    大部分面向对象的编程语言(除了C++)都只支持单继承,而不支持多继承,为什么呢?因为多继承不仅增加编程复杂度,而且容易导致莫名其妙的错误. Python虽然语法上支持多继承,但是却不推荐使用多继承,而 ...

  5. javascript高级程序设计学习历程

    第三章 基本概念 3.1 语法 3.1.1 区分大小写 ECMAScript中的一切(变量,函数,操作符)都区分大小写的 3.1.2 标识符 标识符:变量,函数,属性的名字以及函数的参数. 标识符的命 ...

  6. AI:WEB:1 Walkthrough

    AI: Web: 1 Vulnhub Walkthrough靶机下载:https://www.vulnhub.com/entry/ai-web-1,353/测试方法:    Nmap网络扫描    浏 ...

  7. C++ OpenSSL 之五:生成P12文件

    1.等同于使用: openssl pkcs12 -export -inkey "key_path" -in "pem_path" -out "save ...

  8. 【Spring AOP】Spring AOP之你必须知道的AOP相关概念(1)

    一.什么是AOP AOP(Aspect-oriented Programming)即面向切面编程,是对OOP( Object-oriented Programming)即面向对象编程的一种补充,AOP ...

  9. Game Engine Architecture 12

    [Game Engine Architecture 12] 1.the field of physics is vast, and what most of today’s game engines ...

  10. 大数据技术原理与应用【第五讲】NoSQL数据库:5.4 NoSQL的三大基石

    NoSQL的三大基石:cap,Base,最终一致性   5.4.1 cap理论(帽子理论):   consistency:一致性availability:可用性partition tolerance: ...