sprootBoot上传和下载文件

发布于:2021-10-19 13:38:07

1.单文件上传:传到服务器的 F:uploadSrc目录下


@RequestMapping("/upload")
public @ResponseBody
String upload(@RequestParam("file") MultipartFile file){
try {
if(file.isEmpty()){
return "file is empty";
}
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String filePath = "F:\uploadSrc\";
String path = filePath+fileName;
File dest = new File(path);
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return "upload success";

}catch (IllegalStateException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
return "upload failed";
}

2.多文件上传:目录同上


@PostMapping("/batch")
public @ResponseBody
String handleFileUpload(HttpServletRequest request){
List fileList = ((MultipartHttpServletRequest)request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for(int i=0;i file = fileList.get(i);
String filePath = "F:\uploadSrc\";
if(!file.isEmpty()){
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+file.getOriginalFilename())));
stream.write(bytes);
stream.close();
}catch (Exception e){
stream = null;
e.printStackTrace();
return "the"+i+"file upload failure";
}
}else {
return "the"+i+"file is empty";
}
}
return "upload multiFile success";
}

3.下载文件:


@GetMapping("/download")
@ResponseBody
public String downloadFile(HttpServletRequest request, HttpServletResponse response){
String fileName = "img11.png"; //下载时的文件名
if(fileName!=null){
File file = new File("F:\downSrc\img11.png");
if(file.exists()){
response.setContentType("application/force-download");
response.addHeader("Content-Disposition","attachment;fileName="+fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i!=-1){
os.write(buffer,0,i);
i = bis.read(buffer);
}
bis.close();
fis.close();
return "download success";
}catch (Exception e){
e.printStackTrace();
}
}
}
return "failure";
}

4:调试,可以用谷歌的postman或安卓调试也可以,这里使用安卓的xutils框架调试,由于我的电脑本地服务器连我的热点,可以使用ipconfig查看ip,然后使用即可。
下载:


fun checkNewVersionApk(){
var url = "http://ip:8080/download"
var params = RequestParams(url)
var ss = Environment.getExternalStorageDirectory().path+"/apk/111.png"
params.saveFilePath = ss
x.http().get(params,object :Callback.ProgressCallback{
override fun onFinished() {
Log.d("download","finished:"+ss)
}

override fun onLoading(total: Long, current: Long, isDownloading: Boolean) {
//下载中的进度
Log.d("download","onLoading")
}

override fun onStarted() {

}

override fun onSuccess(result: File?) {
//下载完成
// var intent = Intent(Intent.ACTION_VIEW)
// intent.setDataAndType(Uri.fromFile(result),"application/vnd.android.package-archive")
// startActivity(intent)
Log.d("download","onSuccess")
}

override fun onWaiting() {

}

override fun onCancelled(cex: Callback.CancelledException?) {
}

override fun onError(ex: Throwable?, isOnCallback: Boolean) {
Log.d("download","onError"+ex.toString())
}

})
}

上传:


fun upLoadFile(filePath:String){
var path = filePath
var params = RequestParams("http://ip:8080/upload")
params.isMultipart = true
params.addBodyParameter("file",File(path))
x.http().post(params,object :Callback.CommonCallback{
override fun onFinished() {

}

override fun onSuccess(result: String?) {
Log.d("upload","onSuccess")
}

override fun onCancelled(cex: Callback.CancelledException?) {
}

override fun onError(ex: Throwable?, isOnCallback: Boolean) {
Log.d("upload","onError"+ex.toString())
}

})
}

如果使用知乎的图片选择框架,返回uri后,得转为真正的地址:


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode==111&&resultCode== Activity.RESULT_OK){
val result = Matisse.obtainResult(data)
Glide.with(this).load(result.get(0)).into(glideImage);
if(result!=null&&result.size>0) {
for (item in result) {
Log.d("matisse", item.toString());
var uploadUrl = getRealPathFromUri(this@MainActivity,item)
Log.d("matisse",uploadUrl)
upLoadFile(uploadUrl);
}
}else{
Log.d("matisse", "error");
}
}
}

转换地址:


public fun getRealPathFromUri(context:Context, contentUri:Uri):String {
var cursor: Cursor? = null
try {
var proj = arrayOf(MediaStore.Images.Media.DATA )
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
var column_index:Int = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}

到此,服务器的下载上传和客户端的上传下载都完毕了,后面搞搞neety,在项目里加点聊天功能,实现客户端的聊天,不知道难不难,哈哈。

相关推荐

最新更新

猜你喜欢