我的qq 2038373094
使用的组件
这个组件的作用
1、把用户上传的图片拷贝到千牛云服务器上
2、然后千牛云返回一个图片链接blob:http://localhost:8088/42786950-1ef1-44a3-8315-f3f7d83ed9fc
我们现在要实现的是把用户上传的图片传到本地服务器,然后返回一个本地的形式的链接
1、配置跨域请求
2、更改组件的配置
action="异域格式的接口请求"
原本访问的是后台地址是 http://localhost:8080/PsychoSys/returnurl.action
现在的地址是 /api/PsychoSys/returnurl.action
这个很重要,如果不这样写,会报错
3、把从后台返回的地址,赋值给imageUrl
handleAvatarSuccess(res, file) {
this.form.imageUrl =res;
},
后台部分
我是用java的ssh框架实现的
package cn.com.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import cn.com.tools.RandomStr;
@Repository(value="saveImg")
@Scope("prototype")
public class SaveImg {
private File file;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
@Transactional
public String copyfile(){
//url
String url="http://localhost:8080/PsychoSys/img/";
String fn=RandomStr.getRandomString(10);
//文件的拷贝
//存储图片的地址
HttpServletRequest request = ServletActionContext.getRequest();
String dsk=request.getSession().getServletContext().getRealPath("/img");
String cfn=dsk+"/"+fn+".jpg";
File fl=new File(cfn);
FileOutputStream fout=null;
InputStream in=null;
try {
fout=new FileOutputStream(fl);
in=new FileInputStream(file);
byte [] by=new byte[1024];
int length=0;
try {
while((length=in.read(by))>-1){
fout.write(by, 0, length);
}
url=url+fn+".jpg";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(in!=null){
in.close();
}
if(fout!=null){
fout.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//把地址
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
try {
response.getWriter().write(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}