配置Tomcat

1.1、添加upload文件夹

在webapps\Root文件夹下创建用于接收上传文件的upload文件夹

1.2、修改conf\web.xml设置允许上传文件

		<init-param>
            <param-name>readonly</param-name>
            <param-value>false</param-value>
        </init-param>

1.3、修改conf\server.xml设置端口号,避免跟springboot冲突

<Connector port="8060" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"  URIEncoding="UTF-8"/>

二、uni-app代码:

               //_self为在export default外面作用域外定义的全局变量,用来等价代换
				_self = this;
				//第一步:打开手机相册或者文件管理器选择文件
				uni.chooseImage({
					count:1,//允许上传一张图片
					sizeType:['original','compressed'],//可以指定是原图还是压缩图,默认二者都有
					sourceType:['album'],//从相册选择
					success:function(res){
						//获得选择好的文件,就算只有一个文件也是数组
						const tempFilePaths = res.tempFilePaths;
						
						//第二步:把选择的文件上传到服务器
						const uploadTask = uni.uploadFile({
							url:'http://localhost:8070/upload/file',//后端接口url
							filePath:tempFilePaths[0],
							name:'fileName',//和后端接口需要的参数名一致
							success: (res) => {
								console.log("图片路径为:"+res.data)
								_self.formData.logoPath=res.data//获取到图片路径
							}
						})
						//获取文件的上传进度
						uploadTask.onProgressUpdate(function(res){
							console.log('上传进度:'+res.progress)
							console.log('已经上传的数据长度:'+res.totalBytesSent)
							console.log('预计需要上传的数据总长度:'+res.totalBytesExpectedToSend)
						})
					}
				})

如果是文件:

上传文件方法也可以上传图片,只需要把extension中改为图片对应为后缀名即可

	 _self = this;
				uni.chooseFile({
					
					//第一步:选择文件
				  count: 1, //默认100
				  extension:['.pdf','.doc','.xlsx','.docx','.xls'],
					success: function (res) {
						const tempFilePaths = res.tempFilePaths;//若果只选择一个文件,这个文件就是数组的第一个元素
						//第二步:把选择的文件上传到服务器
						uni.uploadFile({
							url:'http://localhost:8070/upload/file',
							filePath:tempFilePaths[0],
							name:'fileName',
							success: (res) => {
								console.log(res.data)
								 _self.formData.attachmentpath = res.data
							}
							
						})
					}
				})
			}

三、spring boot代码:

 JesyFileUpload工具类:
  /**
     * 上传文件
     *
     * @param file --文件名
     * @param serverUrl --服务器路径http://127.0.0.1:8080/ssm_image_server
     * @return
     * @throws IOException
     */
    public static String uploadFile(MultipartFile file, String serverUrl) throws IOException {
        //重新设置文件名
        String newFileName = new Date().getTime()+""; //将当前时间获得的毫秒数拼接到新的文件名上
        //随机生成一个3位的随机数
        Random r = new Random();
        for(int i=0; i<3; i++) {
            newFileName += r.nextInt(10); //生成一个0-10之间的随机整数
        }

        //获取文件的扩展名
        String orginalFilename = file.getOriginalFilename();
        String suffix = orginalFilename.substring(orginalFilename.indexOf("."));

        //创建jesy服务器,进行跨服务器上传
        Client client = Client.create();
        //把文件关联到远程服务器
        //例如:http://127.0.0.1:8080/ssm_image_server/upload/123131312321.jpg
        WebResource resource = client.resource(serverUrl+"/"+newFileName+suffix);
        //上传
        //获取文件的上传流
        resource.put(String.class, file.getBytes());

        //图片上传成功后要做的事儿
        //1、ajax回调函数做图片回显(需要图片的完整路径)
        //2、将图片的路径保存到数据库(需要图片的相对路径)
//        String fullPath = serverUrl+"/upload/"+newFileName+suffix; //全路径
        String relativePath = "/upload/"+newFileName+suffix; //相对路径

        return relativePath;
    }

controller:

@RestController
@RequestMapping("/upload")
@CrossOrigin(origins = "*")
public class UploadController {
    @PostMapping("/file")
    public String upload(MultipartFile fileName) {
        String path = "";
        try {
            path=JesyFileUploadUtil.uploadFile(fileName, "http://localhost:8060/upload");//"http://localhost:8060/upload"为文件服务器访问路径,这里用的是用Tomcat
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐