图片上传:
import com.pws.bookshop.util.ResultCode;
import com.pws.bookshop.util.ResultVO;
import com.pws.bookshop.exception.CustomizeException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/upload")
public class ImageUploadController {
@PostMapping("/book_image")
public ResultVO uploadBookImage(MultipartFile bookImage, HttpServletRequest request) {
String path = "src/main/resources/static/images/book_images";
File pathFile=new File("src/main/resources/static/images/book_images");
System.out.println(pathFile.getAbsolutePath());
String targetFileName=bookImage.getOriginalFilename();
File targetFile = new File(pathFile.getAbsolutePath(), targetFileName);
try {
bookImage.transferTo(targetFile);
} catch (IOException e) {
e.printStackTrace();
throw new CustomizeException(ResultCode.FAILED, "上传图片失败");
}
return new ResultVO(ResultCode.SUCCESS,targetFileName);
}
}
在这里插入代码片上传接口前端 页面
<div class="layui-form-item">
<label class="layui-form-label">上传图片</label>
<div class="layui-input-block">
<button type="button" class="layui-btn" id="upload-book-image">
<i class="layui-icon"></i>上传图片
</button>
<input type="text" id="image" name="image" autocomplete="off" class="layui-input" style="display: none;">
</div>
</div>
js
var uploadInst = upload.render({
elem: '#upload-book-image',
url: '/upload/book_image',
accept: 'images',
acceptMime: 'image/*',
size: 1024*2 ,
field:'bookImage',
done: function (res) {
if(res.code!=0){
return layer.msg(res.msg,{icon:2});
}
$("#image").val(res.data);
return layer.msg("上传成功",{icon:1});
},
error: function () {
}
});
因为上传图片到static目录下需要重启项目所以要用拦截器
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String path = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\images\\book_images";
registry.addResourceHandler("/images/**").addResourceLocations("file:"+path);
}
}
|