HBuilder的上传文件

1.在HBuilder中修改pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<!-- SpringBoot支持01、parent:Begin -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
	</parent>
	<!-- SpringBoot支持01、parent:End -->
 
	<groupId>org.personal.qin.demos</groupId>
	<artifactId>upload_demo</artifactId>
	<version>1.0.0-SNAPSHOT</version>
	<packaging>jar</packaging>
 
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<!-- java版本 -->
		<java.version>1.8</java.version>
	</properties>
 
	<dependencies>
		<!-- SpringBoot:Begin -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- SpringBoot:End -->
 
		<!-- SpringMVC:Begin -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>
		<!-- SpringMVC:End -->
		
		<!-- 文件上传:Begin -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<!-- 文件上传:End -->
		<!--跨服务器上传:Begin -->
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-client</artifactId>
			<version>1.19</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-core</artifactId>
			<version>1.19</version>
		</dependency>
		<!--跨服务器上传:End -->
 
	</dependencies>
 
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<!-- 资源文件拷贝插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- java编译插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- SpringBoot支持03、添加SpringBoot的插件支持:Begin -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<!-- SpringBoot支持03、添加SpringBoot的插件支持:End -->
		</plugins>
	</build>
</project>

2.utiles下添加JesyFileUploadUtil文件

package com.rz.cms.server.main.utils;
 
import java.io.IOException;
import java.util.Date;
import java.util.Random;
 
import javax.net.ssl.SSLContext;
 
 
import org.springframework.web.multipart.MultipartFile;
 
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
 
 
/**
 * 跨服务器文件上传工具类
 * 
 * @author qin
 *
 */
public class JesyFileUploadUtil {
 
	/**
	 * 上传文件
	 * 
	 * @param file --多媒体文件
//	 * @param servlerUrl --服务器路径http://127.0.0.1:8080/ssm_image_server
	 * @return
	 * @throws IOException 
	 */
	public static FileInfo uploadFile(MultipartFile file, String serverUrl) throws IOException {
		//把request请求转换成多媒体的请求对象
//		MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request;
		//根据文件名获取文件对象
//		MultipartFile cm = mh.getFile(fileName);
		//获取文件的上传流
		byte[] fbytes = file.getBytes();
		
		//重新设置文件名
		String newFileName = "";
		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(getClientConfig());
		Client client = Client.create();
		//把文件关联到远程服务器
		//http://127.0.0.1:8080/ssm_image_server/upload/123131312321.jpg
		WebResource resource = client.resource(serverUrl+"/upload/"+newFileName+suffix);
		//上传
		resource.put(String.class, fbytes);
		
		//图片上传成功后要做的事儿
		//1、ajax回调函数做图片回显(需要图片的完整路径)
		//2、将图片的路径保存到数据库(需要图片的相对路径)
		String fullPath = serverUrl+"/upload/"+newFileName+suffix; //全路径
		String relativePath = "/upload/"+newFileName+suffix; //相对路径
		
//		//生成一个json响应给客户端
//		String resultJson = "{\"fullPath\":\""+fullPath+"\", \"relativePath\":\""+relativePath+"\"}";
//		return resultJson;
		
		return new FileInfo(newFileName+suffix, false, fullPath, relativePath);
	}
	
	
//	@SuppressWarnings("unused")
//	private static ClientConfig getClientConfig() {
//		SslConfigurator sslConfig = SslConfigurator.newInstance();
//		sslConfig.trustStoreFile("src/main/resources/lvxingfw.jks")
//		.trustStorePassword("lxfw2021");
//		sslConfig.securityProtocol("SSL");
//    	SSLContext sslContext = sslConfig.createSSLContext();
//
//	    ClientConfig cc = new DefaultClientConfig();
//	    cc.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
//	    		new HTTPSProperties(new MyHostnameVerifier(), sslContext));
//
//	    return cc;cc
//	}
}

3. utiles下添加FileInfo文件

package com.rz.cms.server.main.utils;
 
public class FileInfo {
 
	private String fileName;
	private boolean isSecret;
	private String absolutPath;
	private String relativePath;
 
	public String getFileName() {
		return fileName;
	}
 
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
 
	public String getAbsolutPath() {
		return absolutPath;
	}
 
	public void setAbsolutPath(String absolutPath) {
		this.absolutPath = absolutPath;
	}
 
	public String getRelativePath() {
		return relativePath;
	}
 
	public void setRelativePath(String relativePath) {
		this.relativePath = relativePath;
	}
 
	public boolean isSecret() {
		return isSecret;
	}
 
	public void setSecret(boolean isSecret) {
		this.isSecret = isSecret;
	}
 
	public FileInfo() {
	}
 
	public FileInfo(String fileName, boolean isSecret, String absolutPath, String relativePath) {
		super();
		this.fileName = fileName;
		this.isSecret = isSecret;
		this.absolutPath = absolutPath;
		this.relativePath = relativePath;
	}
 
	@Override
	public String toString() {
		return "FileInfo [fileName=" + fileName + ", isSecret=" + isSecret + ", absolutPath=" + absolutPath
				+ ", relativePath=" + relativePath + "]";
	}
 
}

4.Controller下添加FileController跨越文件

package com.rz.cms.server.main.controller;
 
import com.rz.cms.server.main.utils.FileInfo;
import com.rz.cms.server.main.utils.HttpResult;
import com.rz.cms.server.main.utils.JesyFileUploadUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.IOException;
 
@RestController
@RequestMapping("upload")
public class FileController {
 
    @CrossOrigin(origins = "*")
    @PostMapping("file")
    @ResponseBody
    public String upload(MultipartFile file){
        String result = null;
 
        try {
            FileInfo fileInfo = JesyFileUploadUtil.uploadFile(file, "http://localhost:8060");
            result = fileInfo.getRelativePath();
        } catch (IOException e) {
            e.printStackTrace();
            result = "";
        }
 
        return result;
    }
}

5.页面效果如图

 6. 基础效果图首先写出图片效果

<uni-nav-bar @clickRight="save" @clickLeft="back()" fixed="true" leftIcon="back" leftText="返回" right-text="保存"
   title="添加文章"></uni-nav-bar>
 
  <uni-group title="文章管理: 添加文章" top="10" mode="card">
   <view style="width: 1000rpx; margin-left: auto; margin-right: auto;">
    <view style="margin-bottom: 15rpx;">文章标题</view>
    <input singleline="true" placeholder="标题是必填项" type="text" v-model="articleTitle"
     style="border: 1px solid #000000; border-radius: 5rpx; line-height: 40rpx; height: 40rpx; width: 1000rpx; margin-bottom: 35rpx; padding: 10rpx;" />
 
    <view style="margin-bottom: 15rpx;">文章描述</view>
    <textarea placeholder-style="color:#F76260" placeholder="描述内容建议在70字以内" v-model="articleDescr"
     style="border: 1px solid #000000; border-radius: 5rpx; height: 300rpx; width: 1000rpx; padding: 10rpx; margin-bottom: 35rpx;" />
 
    <view style="margin-bottom: 15rpx;">选择标题图(图片分辨率建议为:200px * 200px)</view>
    <button type="primary" :loading="loading" :disabled="btnState" @click="upload">选择照片</button>
   </view>
  </uni-group>
  <!-- 提示框 -->
  <uni-popup ref="popup" type="dialog">
   <uni-popup-dialog mode="base" title="通知" :content="msg" :duration="2000" :before-close="true" @close="close"
    @confirm="confirm"></uni-popup-dialog>
  </uni-popup>

7.参考

upload(){
				_self = this;
				//图片选择API
				uni.chooseImage({
					count:1,//一次只能选择一个文件
					sizeType: ['original','compressed'],  //可以指定上传的图片是否压缩还是原图 默认全有
					sourceType:['album']  ,//从相册选择图片
					success: function(res){
						const tempFilePaths = res.tempFilePaths;//const声明后其值不可变
						//uni-app的图片上传API
						const uploadTask = uni.uploadFile({
							url:'http://localhost:8070/upload/file',
							filePath:tempFilePaths[0],
							name:'file',
							success:function(uploadFileRes){
								_self.relativePath = uploadFileRes.data;
								
							}
						});
						
						uploadTask.onProgressUpdate(function(res){
							_self.percent = res.progress;//获得文件上传的进度
							console.log("上传进度:"+res.progress);
							console.log("已经上传的进度:"+res.totalBytesSent);
							console.log("预计需要上传的数据总长度:"+res.totalBytesExpectedToSend);
						});
					}
				});
				
			}

8.下面是中转站return里所需要的东西同样含义也进行了注释

return{
				msg:null,
				articleTitle:null,//文章标题
				articleDescr:null,//文章简介
				btnState:false,//上传禁止使用按钮  flase是不禁用
				percent:0,//进度条
				loading:false,//是否显示进度条
				fileName:null,//上传的名称
				relativePath:null,//文件上传后 后台返回的路径
				cid:null
			}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值