第一步:先从相册获取图片,将图片转换为File ,然后上传图片到服务器
public class uploadLicensePicture extends AppCompatActivity {
private Button getPicture_Button;
private ImageView imageview_upload_Picture;
private Button uploadPicture_Button;
private static final int REQUEST_CODE_PICK_IMAGE = 222;
String CONTENT_TYPE = "multipart/form-data";
String BOUNDARY = UUID.randomUUID().toString();
private static final int TIME_OUT = 10*1000; //超时时间
private static final String CHARSET = "utf-8"; //设置编码
private Uri uri;
private String path;
private int mTargetW;
private int mTargetH;
String PREFIX = "--", LINE_END = "\r\n";
private static final String TAG = "uploadLicensePicture";
private Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_license_picture);
getPicture_Button = (Button) findViewById(R.id.getPicture_Button);
imageview_upload_Picture = (ImageView) findViewById(R.id.imageview_upload_Picture);
uploadPicture_Button = (Button) findViewById(R.id.uploadPicture_Button);
getPicture_Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//从相册获取图片,这一步是在相册选择图片
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");//相片类型
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
}
});
uploadPicture_Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File file=new File(Environment.getExternalStorageDirectory(), Const.licensepicture);//将要保存图片的路径
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (file==null){
Log.e(TAG, "onClick: nulnullnullnullnullnullnullnulllnullnullnullnullnullnull" );
}
Log.e(TAG, "onClick: "+file.getAbsolutePath() );
uploadPicture(null);
}
});
}
//返回相册里面的图片
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mTargetH = imageview_upload_Picture.getMaxHeight();
mTargetW = imageview_upload_Picture.getMaxWidth();
switch (requestCode) {
//获取相册的图片
case REQUEST_CODE_PICK_IMAGE:
if (data == null) return;
uri = data.getData();
int sdkVersion = Integer.valueOf(Build.VERSION.SDK);
if (sdkVersion >= 19) {
path = this.uri.getPath();
path = PictureUtils.getPath_above19(uploadLicensePicture.this, this.uri);
} else {
path = PictureUtils.getFilePath_below19(uploadLicensePicture.this, this.uri);
}
break;
}
imageview_upload_Picture.setImageBitmap(PictureUtils.getSmallBitmap(path, mTargetW, mTargetH));
bitmap = PictureUtils.getSmallBitmap(path,mTargetW,mTargetH);
}
private void uploadPicture(String imagePath) {
Log.i("start upload", "start upload");
Log.i("start upload_path", "imagePath" + imagePath);
NetworkTask networkTask = new NetworkTask();
networkTask.execute(imagePath);
}
class NetworkTask extends AsyncTask<String, Integer, String> {
private final String ServerURL="http://localhost:8080/yuyu/storeByAdmin/uploadlicense.do";
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
//String uri = (params[0]);
//Uri u=Uri.parse((String) uri);
File file = new File(Environment.getExternalStorageDirectory(), Const.licensepicture);
return UploadUtils.uploadFile(file, ServerURL);
}
@Override
protected void onPostExecute(String result) {
if (UploadUtils.SUCCESS.equalsIgnoreCase(result)) {
Log.i("上传结果", "上传成功 ");
} else {
Log.i("上传结果", "上传失败 ");
}
}
}
网上找的UploadUtils工具类
public class UploadUtils {
private static final int TIME_OUT = 10 * 10000000; //超时时间
private static final String CHARSET = "utf-8"; //设置编码
public static final String SUCCESS = "1";
public static final String FAILURE = "0";
public static String uploadFile(File file, String RequestURL) {
String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); //允许输入流
conn.setDoOutput(true); //允许输出流
conn.setUseCaches(false); //不允许使用缓存
conn.setRequestMethod("POST"); //请求方式
conn.setRequestProperty("Charset", CHARSET); //设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", "multipart/form-data" + ";boundary=" + BOUNDARY);
if (file != null) {
OutputStream outputSteam = conn.getOutputStream();
DataOutputStream dos = new DataOutputStream(outputSteam);
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意:
* name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
Log.i("file.getName()",file.getName());
sb.append("Content-Disposition: form-data; name=\"upload_file\"; filename=\"" + file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
dos.close();
/**
* 获取响应码 200=成功
* 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
Log.e("response code", "response code:" + res);
if (res == 200) {
return SUCCESS;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return FAILURE;
}
第二步:服务器端将图片上传到ftp图片服务器
@RequestMapping(value = "uploadlicense.do")
@ResponseBody
public ServerResponse uploadlicense(@RequestParam(value="upload_file") MultipartFile file, HttpServletRequest request) {
String path = request.getSession().getServletContext().getRealPath("upload");
String targetFileName = iFileService.upload(file, path);
String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
Map fileMap = Maps.newHashMap();
fileMap.put("uri", targetFileName);
fileMap.put("url", url);
return ServerResponse.createBySuccess(fileMap);
}
@Service("iFileService")
public class FileServiceImpl implements IFileService {
private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
@Override
public String upload(MultipartFile file, String path) {
String fileName = file.getOriginalFilename();
//获取扩展名
String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);
//
String uploadfileName = UUID.randomUUID().toString() + "." + fileExtensionName;
logger.info("开始上传文件,上传文件的文件名:{},上传的路径:{},新文件名:{}", fileName, path, uploadfileName);
File fileDir = new File(path);
if (!fileDir.exists()) {
fileDir.setExecutable(true);
fileDir.mkdirs();
}
File targetFile = new File(path, uploadfileName);
try {
file.transferTo(targetFile);
//todo 将targetFile上传到我们的FTP服务器上
FTPUtil.uploadFile(Lists.newArrayList(targetFile));
//已经上传到ftp服务器上
//todo 上传完之后,删除upload下面的文件
//targetFile.delete();
} catch (IOException e) {
logger.error("上传文件异常", e);
return null;
}
return targetFile.getName();
}
}
private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);
private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
private static String ftpUser = PropertiesUtil.getProperty("ftp.user");
private static String ftpPass = PropertiesUtil.getProperty("ftp.pass");
public FTPUtil(String ip, int port, String user, String pwd) {
this.ip = ip;
this.port = port;
this.user = user;
this.pwd = pwd;
}
public static boolean uploadFile(List<File> fileList) throws IOException {
FTPUtil ftpUtil = new FTPUtil(ftpIp, 21, ftpUser, ftpPass);
logger.info("开始连接ftp服务器");
boolean result = ftpUtil.uploadFile("/home/yu/image/", fileList);
logger.info("结束上传,上传结束:{}");
return result;
}
private boolean uploadFile(String remotePath, List<File> fileList) throws IOException {
boolean uploaded = true;
FileInputStream fis = null;
//连接ftp服务器
if (connectServer(this.ip, this.port, this.user, this.pwd)) {
try {
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
for (File fileItem : fileList) {
fis = new FileInputStream(fileItem);
ftpClient.storeFile(fileItem.getName(), fis);
}
} catch (IOException e) {
logger.error("上传文件异常", e);
uploaded = false;
e.printStackTrace();
} finally {
fis.close();
ftpClient.disconnect();
}
}
return uploaded;
}
private boolean connectServer(String ip,int port,String user,String pwd){
boolean isSuccess = false;
ftpClient = new FTPClient();
try {
ftpClient.connect(ip);
isSuccess = ftpClient.login(user,pwd);
} catch (IOException e) {
logger.error("连接服务器异常",e);
}
return isSuccess;
}
private String ip;
private int port;
private String user;
private String pwd;
private FTPClient ftpClient;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}